【问题标题】:Angular2 unit testing - why nativeElement has empty CSSStyleDeclarationAngular2 单元测试 - 为什么 nativeElement 有空的 CSSStyleDeclaration
【发布时间】:2017-07-09 23:59:17
【问题描述】:

我正在尝试测试一个简单的标题组件,该组件具有一个按钮,并且在获得焦点时 - 仅使用 css 可见性属性打开一个下拉列表。

这是html:

<nav class="navigation">
    <button type="button">
        <span>click here</span>
    </button>
    <ul>
        <li> Text </li>
        <li> Text </li>
        <li> Text </li>
    </ul>
</nav>

这是scss风格:

button {

    span {
        margin-right: 10px;
    }

    &:focus {

        + ul {
            visibility: visible;
        } 
    }
}

ul {
    position: absolute;
    list-style: none;
    z-index: 1000;
    visibility: hidden;
    transition: visibility 0.1s linear;
    background-color: $color-primary;
}

这是测试:

it('should open dropdown on focus', () => {

    let button = fixture.debugElement.query(By.css('button'));
    button.triggerEventHandler('focus', null);

    fixture.detectChanges();
    let dropdownElement = fixture.debugElement.query(By.css('ul')).nativeElement;

    console.log(dropdownElement);
    console.log(dropdownElement.style);

    expect(dropdownElement.style['visibility']).toBe('visible');

});

当我运行测试时,我可以看到 console.log(dropdownElement) 存在并且 console.log(button.nativeElement) 返回 CSSStyleDeclaration 对象 - 但所有属性都有一个空字符串作为值:

CSSStyleDeclaration {
    alignContent: ""
    alignSelf: ""
    ...
    ...
    ...
    color: ""
    visibility: ""
    ...
    ...
}

所以基本上我需要的是触发按钮上的焦点事件,然后查看下拉的 css/style 属性“可见性”的值是否为“可见”。 我不知道出了什么问题,因为我可以看到 Karma-Debug 中的一切都很好,但所有样式属性都是空的……知道问题出在哪里吗?

【问题讨论】:

    标签: unit-testing angular karma-jasmine typescript2.0 angular2-testing


    【解决方案1】:

    我在运行时遇到了类似的问题(不是测试)。 Style 属性是静态的,并且基于 html 元素上的初始样式属性,因此不会动态更新。 解决方案是使用Window.getComputedStyle()。此函数从样式表计算(当前!)样式。

    【讨论】:

      猜你喜欢
      • 2016-10-08
      • 2020-05-09
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多