【问题标题】:Angular 2 + Jasmine - Test whether an element is visibleAngular 2 + Jasmine - 测试元素是否可见
【发布时间】:2017-02-20 13:43:36
【问题描述】:

我正在测试一个使用 Angular (2+) 制作的网络应用程序,我正在使用 Jasmine + Karma 作为测试环境。 我进行了很多搜索,但无法测试元素是否可见,我想我会从 Angular 中找到一个罐装匹配器或一些实用方法,但我没有。
我尝试使用HTMLElement 的classList 属性,测试:visible,但这不起作用。
我觉得我缺少一些基本的东西,因为它应该是基本的东西。
那么,在下面的示例中,如何测试 id 为 header-menu-dropdown-button 的 div 是否可见?

这是我正在努力的测试方法:

模板

<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>

测试

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
}); 

注意:showMenu 方法只是切换 showUserMenu 布尔值。

【问题讨论】:

    标签: unit-testing angular jasmine


    【解决方案1】:

    我通过检查隐藏属性的存在来对其进行单元测试。

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

    【讨论】:

    • 这个答案现在过时了吗?
    • 是的,应该是expect(menuDropDownButtonEl.attributes('hidden')).toEqual(true);
    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 2017-08-17
    • 2016-01-19
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多