Angular组件@Input传值后class已生效,测试获取backgroundColor失败
问题根因
HTMLElement.style 仅支持读取元素行内样式(即直接写在标签style属性上的样式),通过.comp--red类设置的样式属于外部样式表规则,不会被该属性读取,因此拿到空字符串导致断言失败。
解决方案
方案1:验证最终渲染样式
使用getComputedStyle读取浏览器计算后的最终样式,注意匹配浏览器默认返回的RGB颜色格式:
it('should have red background when type is red', () => { fixture.componentInstance.type = 'red'; fixture.detectChanges(); const div = fixture.debugElement.query(By.css('.comp--red')).nativeElement; expect(window.getComputedStyle(div).backgroundColor).toBe('rgb(255, 0, 0)'); });
提示:如果使用JSDom执行测试,需要确保测试配置已开启样式文件加载,否则
getComputedStyle也无法拿到正确的样式值。
方案2:仅校验类绑定逻辑
单元测试无需覆盖样式渲染效果时,直接断言目标类已正确添加即可,用例执行效率更高:
it('should add correct class when type changes', () => { fixture.componentInstance.type = 'red'; fixture.detectChanges(); const div = fixture.debugElement.query(By.css('div')).nativeElement; expect(div.classList.contains('comp--red')).toBeTrue(); });
内容的提问来源于stack exchange,提问作者abellay
相关产品推荐
相关产品推荐

