I'm having some difficulties with a unit test that reads some html that is added / removed from the DOM using * ngIf.
This is the DOM:
<div class="detailacc" (click)="showDet()"> <i class="fa" [class.fa-caret-right]="!showHideDet " [class.fa-caret-down]="showHideDet " aria-hidden="true"></i> <h4>Expandable</h4> </div> <div *ngIf="showHideDet"> <p class="detailHeader">Details header</p> </div>
This is the component function called when the first div clicks:
private showDet() { console.log('show called'); this.showHideDet = !this.showHideDet; }
And finally, this is the specification:
it('should show the header when the expandable elem is clicked', async(() => { const fixture = TestBed.createComponent(DetailsComponent); const compiled = fixture.debugElement.nativeElement; let detPresent: boolean = false; for (let node of compiled.querySelectorAll('.detailacc')) { node.click(); } setTimeout(() => { console.log(compiled.querySelectorAll('.detailHeader')); for (let node of compiled.querySelectorAll('.detailHeader')) { if (node.textContent === 'Details header') { detPresent = true; break; } } expect(detPresent).toBeFalsy(); }, 0); }));
As you can see, I wrapped a code that searches for those DOM elements that are displayed only when * ngIf is true in setTimeout, as in this How to check if ngIf has taken effect , but I still get nothing.
Also, if you are wondering if this click is called in this test, this is because the console.log icon in the component is displayed in the Karma console. The .log console inside setTimeout shows NodeList (0), basically there are no nodes with the found class .detailHeader.
unit-testing angular karma-runner jasmine
Hazerd
source share