角度测试平台,通过CSS查询,找到伪元素



我正在使用TestBed进行Angular 2+单元测试。 场景,我想验证我的组件,伪元素的颜色。

组件.ts

label::before {
right: 0;
background-color: red;
}
@Component({
selector: 'app-test',
template: `
<div><label>a label</label></div>
`,
styleUrls: ['./test.component.scss'],
})
export class TestComponent {

}

所以当我写单元测试时,我想验证伪元素背景颜色

beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should set background color', () => {
const ele = fixture.debugElement.query(By.css('label::before')).nativeElement; // error here
// not sure how to use by.css to locate on the pseudo element
expect(ele.backgroundColor).toBe('....');
});

我建议以不同的方式编写测试。

夹具属于ComponentFixture<T>类型,其中T是您尝试访问的组件。debugElement属性有两个属性,您在编写测试componentInstance通常对此感兴趣,nativeElement

ComponentInstance是您的组件ts文件。从某种意义上说,这是您的类声明。

顾名思义NativeElement是标记或您的template

我认为不可能按照你建议的方式去做。

但是您可以尝试

const color =  window.getComputedStyle(fixture.debugElement.nativeElement.querySelector('label'), ':after').getPropertyValue('background-color');

这将为您提供一个 rgb 结果,因此对于红色,它将是rgb(255,0,0)

我从: 如何获得伪元素?

试试这个,看看它是否有效。我们必须访问测试中的窗口元素并不是很好,但它可能会解决您的问题。可能创建一个更好的测试,而无需访问我建议的窗口 api。

最新更新