Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 + Jasmine - Test whether an element is visible

I'm testing a web app made using Angular (2+), I'm using Jasmine + Karma as testing environment. I've searched a lot but I'm not able to test whether an element is visible or not, I thought I'd find a canned matcher or some utility method from Angular, but I didn't.
I tried using classList property of HTMLElement, testing for :visible, but that's not working.
I feel I'm missing something basic, since it should be something basic to achieve.
So, in the example below, how I can test that the div with id header-menu-dropdown-button is visible ?

Here's the test method I'm struggling with:

Template

<div id="header-menu-dropdown-button" class="dropdown-closing-level" [hidden]="!showUserMenu" (click)="showMenu($event)"></div>
<ul [hidden]="!showUserMenu" class="dropdown-menu" aria-labelledby="dropdown">
    <li class="dropdown-item"><a href="#">Account</a></li>
    <li class="dropdown-item"><a href="#" (click)="logout($event)">Logout</a></li>
</ul>

Test

beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [RouterTestingModule, TranslationsModule],
        declarations: [ AppHeaderComponent ], // declare the test component
    })
}));

beforeEach(() => {
    fixture = TestBed.createComponent(AppHeaderComponent);
    comp = fixture.componentInstance;
    menuDropDownButtonDe = fixture.debugElement.query(By.css('#header-menu-dropdown-button'));
    menuDropDownButtonEl = menuDropDownButtonDe.nativeElement;
});

it('menu should be closed by default', () =>  {
    //Here I want to check the visibility of the menuDropDownButtonEl element
    expect(menuDropDownButtonEl.classList.contains(":visible")).toBe(false); // <-- not working
}); 

NOTE: showMenu method simply toggles the showUserMenu boolean value.

like image 622
Luigi Dallavalle Avatar asked Feb 20 '17 13:02

Luigi Dallavalle


1 Answers

I unit test it by checking for the existence of the hidden attribute.

expect(menuDropDownButtonEl.hasAttribute('hidden')).toEqual(true);

like image 69
Jordan Heinrichs Avatar answered Sep 28 '22 08:09

Jordan Heinrichs