Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine-Tests - Get elements inside <ng-template> (Angular)

I would like to test HTML elements within a ng-tamplate.

<ng-template>
  <button class="create"></button>
</ng-template>

Jasmine Test:

fixture = TestBed.createComponent(SomeComponent);
const htmlElement: HTMLElement = fixture.nativeElement;
// Does not work:
const p = htmlElement.querySelector('.create');

How can I get the html element inside the ng-template? If I place the button outside of the ng-template tag, it works. I think it has something to do with the shadow dom.

Versions: Jasmine 2.8.0; Angular 5.2.9

like image 858
Fabian Avatar asked May 02 '18 07:05

Fabian


1 Answers

I forgot to call fixture.detectChanges();. Only when you call this method, the component is rendered fully into the DOM (including shadow-DOM-elements). The following code works:

fixture = TestBed.createComponent(SomeComponent);
fixture.detectChanges();
const htmlElement: HTMLElement = fixture.nativeElement;
const p = htmlElement.querySelector('.create');

See https://angular.io/guide/testing#detectchanges for more details.

like image 105
Fabian Avatar answered Nov 02 '22 06:11

Fabian