代码之家  ›  专栏  ›  技术社区  ›  Naresh

在角度单元测试中访问元素的内联样式

  •  1
  • Naresh  · 技术社区  · 8 年前

    在中有一个角度组件,它呈现这样的跨度:

    <span class="buy" [style.width.%]="percent"></span>
    

    在我的单元测试中,我想检查内联样式是否具有正确的百分比。例如,如果组件呈现如下,我想测试百分比是否为50%:

    <span class="buy" style="width: 50%;"></span>
    

    目前这是我能做的最好的:

    const debugElm = fixture.debugElement;
    const htmlElm = debugElm.nativeElement;
    const buyBar = htmlElm.querySelector('.buy');
    expect(buyBar.getAttribute('style')).toEqual('width: 0%;');
    

    我不喜欢测试 style 属性等于字符串 width: 0%; . 有没有更好的方法来访问inline样式的width属性?

    2 回复  |  直到 8 年前
        1
  •  0
  •   lupa    8 年前

    所以人们已经讨论了解决方案,这是我的想法。
    为什么要为“50%”这个数字而烦恼呢?

    如果你的观点是测试“.buy”类的宽度是某个类的50%
    我们只是简单地

    it('element with buy class should have width equal 50% of parent element', () => {})
    

    您的测试用例可以是(假设您有一个父类)

    <div class="parent"><span class="buy" style="width: 50%;"></span></div>
    
    const debugElm = fixture.debugElement;
    const htmlElm = debugElm.nativeElement;
    const parent = htmlElm.querySelector('.parent');
    const buyBar = htmlElm.querySelector('.buy');
    
    const parentStyle = getComputedStyle(parent);
    const barStyle = getComputedStyle(buyBar);
    expect(barStyle.width / parentStyle.width).toEqual(0.5);
    

    这里我只是重用上面其他代码,所以不太确定 expect 函数可以工作。但我认为这可能是您的测试用例的一个解决方案。

        2
  •  0
  •   kshetline    8 年前

    你可以尝试这样的方法:

    const style = document.defaultView.getComputedStyle(buyBar, null);
    expect(style.getPropertyValue('width')).toEqual('0%');
    
    推荐文章