Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an Angular 6 app and writing some unit tests trying to determine if an element is visible or not based solely on the boolean result of an *ngIf directive.

Markup:

<div class="header" *ngIf="show">     <div>...</div> </div> 

spec file:

it('should hide contents if show is false', () => {     const button = debugElement.query(By.css('button')).nativeElement;     button.click();   // this will change show to false     fixture.detectChanges();     expect(debugElement.query(By.css('.header')).nativeElement.style.hidden).toBe(true); }); 

I can't seem to get the hidden attribute from the div. Does angular use another approach to hiding the element from the DOM using the *ngIf directive? Do I need to get another property from the nativeElement?

Thanks!

like image 527
J-man Avatar asked Jul 11 '18 17:07

J-man


People also ask

What is fixture detectChanges ()?

fixture is a wrapper for our component's environment so we can control things like change detection. To trigger change detection we call the function fixture.detectChanges() , now we can update our test spec to: Copy it('login button hidden when the user is authenticated', () => { expect(el. nativeElement. textContent.


1 Answers

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; 
like image 50
Amit Chigadani Avatar answered Sep 24 '22 12:09

Amit Chigadani