How do I unit test if an element is visible when the *ngIf directive is used using Jasmine in Angular

If the element is hidden, then it wont be rendered inside the dom.

You can check

expect(fixture.debugElement.query(By.css('.header'))).toBeUndefined();

EDIT : toBeNull() works better in the above case

expect(fixture.debugElement.query(By.css('.header'))).toBeNull();

And also you have a syntax error while fetching the button element. nativeElement is not a function.

Change it this way :

const button = fixture.debugElement.query(By.css('button')).nativeElement;

When testing if a component is being shown or not using ngIf I try to get the element (in this case you use, i.e., debugElement.query(By.css('.header')).nativeElement) and if it should be shown I expect it to be truthy, otherwise falsy.

Something like this:

it('should hide contents if show is false', () => {
    // should be rendered initially
    expect(debugElement.query(By.css('.header')).nativeElement).toBeTruthy();
    //trigger change
    const button = debugElement.query(By.css('button')).nativeElement;
    button.click();   // this will change show to false
    fixture.detectChanges();
    // should not be rendered
    expect(debugElement.query(By.css('.header')).nativeElement).toBeFalsy();
});

Also, bear in mind that sometimes you need to use ComponentFixture#whenStable to detect when the fixture is stable like this:

  it('should hide contents if show is false', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.whenStable().then(() => {
      // same test code here
    });
  });

See this working test for a component which resembles this scenario.

See [GitHub repository]


Writing test case for *ngIf condition use toBeNull condition.

Try with below code, it works for me.

expect(fixture.debugElement.query(By.css('.header'))).toBeNull();