Issue
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 changingcomponent.DATA
, which I supose makes some changes in the view. -
In the second test, you first query for the
app-datatable
element and then callfixture.detectChanges()
. With this secuence, I suposedatatable
has some content and then it mutates after you call thedetectChanges()
, but as you have accessed it before the change detection the test fails.