Angular2 unit testing - why nativeElement has empty CSSStyleDeclaration

泪湿孤枕 提交于 2019-12-07 13:48:28

问题


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.

This is the html:

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

This is the scss style:

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

And this is the test:

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

});

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: ""
    ...
    ...
}

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?


回答1:


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.



来源:https://stackoverflow.com/questions/42349088/angular2-unit-testing-why-nativeelement-has-empty-cssstyledeclaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!