Angular2单元测试-为什么nativeElement具有空的CSSStyleDeclaration [英] Angular2 unit testing - why nativeElement has empty CSSStyleDeclaration

查看:313
本文介绍了Angular2单元测试-为什么nativeElement具有空的CSSStyleDeclaration的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试一个具有按钮的简单标头组件,当它被聚焦时-仅使用css可见性属性打开一个下拉列表.

I'm trying to test a simple header component that has a button and when being focused - opens a dropdown using just css visibility property.

这是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对象-但是所有属性都有一个空字符串作为值:

When I run the test I can see that console.log(dropdownElement) exists and that console.log(button.nativeElement) returns the CSSStyleDeclaration object - but ALL the properties have an empty string as a value:

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

因此,基本上我需要在按钮上触发焦点事件,然后查看下拉菜单的css/style属性"visibility"的值是否为"visible". 我不知道出了什么问题,因为我可以看到在Karma-Debug中一切都可以正常渲染,但是所有样式属性都为空...知道是什么问题吗?

So basically what I need is to trigger the focus event on the button and then see if the value of the dropdown's css/style property "visibility" is "visible". I can't figure what's wrong, cause i can see that everything is rendering fine in Karma-Debug but all the style properties are empty... any idea what's the problem?

推荐答案

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

I've had similar problem in runtime (not tests). Style property is static and based on initial style attribute on html element so this is not updated dynamically. Solution is to use Window.getComputedStyle(). This function calculates (current!) styles from stylesheets.

这篇关于Angular2单元测试-为什么nativeElement具有空的CSSStyleDeclaration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆