如何在角度单元测试中访问 .css 文件中存在的样式

kar*_*sys 4 css unit-testing typescript karma-jasmine angular

我正在为角度应用程序运行单元测试,我尝试从单元测试内的 .css 访问样式。我会让你知道我尝试了什么

 component.listedIps.length=0;
 fixture.detectChanges();

 let whitelistipsdiv=fixture.debugElement.query(By.css('.divAllAllowedIPs'));

 //unit test for style, test for  background-color to be green
 expect(whitelistipsdiv.nativeElement.style.backgroundColor).toEqual('green');// to be darkgreen, here it is null
Run Code Online (Sandbox Code Playgroud)

.css 文件

.divAllAllowedIPs {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*vek 16

我知道我来晚了,但你可以试试。它将 100% 工作

  it('should have green background', () => {
    const e = fixture.debugElement.query(By.css(".divAllAllowedIPs")).nativeElement;
    expect(getComputedStyle(e).backgroundColor).toEqual('rgb(0, 128, 0)');
  });
Run Code Online (Sandbox Code Playgroud)

我希望它也能帮助其他正在寻找类似问题的人