Search code examples
angularjasminekarma-jasmineangular-test

Angular testing DOM elements with *ngIf


Why does this test pass

it ('should hide datatable if data is undefined', () => {
  component.DATA = undefined;
  fixture.detectChanges();
  expect(fixture.debugElement.query(By.css('app-datatable'))).toBeNull();
});

but this doesn't

it ('should hide datatable if data is undefined', () => {
  component.DATA = undefined;
  const datatable = fixture.debugElement.query(By.css('app-datatable'));
  fixture.detectChanges();
  expect(datatable).toBeNull();
});

For the second test suite I receive following error
Error: Expected DebugElement__POST_R3__({ nativeNode: }) to be null.

This is the code of the DOM

<app-datatable *ngIf="DATA"></app-datatable>

Solution

  • It has relation with the way you ran Angular's change detection:

    • In the first test, you run fixture.detectChanges() just after changing component.DATA, which I suppose makes some changes in the view.

    • In the second test, you first query for the app-datatable element and then call fixture.detectChanges(). With this sequence, I suppose datatable has some content and then it mutates after you call the detectChanges(), but as you have accessed it before the change detection the test fails.