我正在尝试创建一个带有测试的组件.该组件具有我想要测试的外部CSS.我想我做的一切都是正确的,但我无法通过测试.这是我的代码:
app.component.spec.ts
app.component.spec.ts
import { AppComponent } from "./app.component"; import { async,TestBed } from "@angular/core/testing"; import { By } from "@angular/platform-browser"; describe("App Component",function () { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [AppComponent],}).compileComponents() })); it("should instantiate component",() => { let fixture = TestBed.createComponent(AppComponent); expect(fixture.componentInstance instanceof AppComponent).toBe(true); }); it("should have expected <h1> text",() => { let fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); let h1 = fixture.debugElement.query(By.css("h1")); expect(h1.nativeElement.innerText).toBe("hello world!"); expect(h1.nativeElement.style.color).toBe("blue"); }); });
app.component.ts:
import { Component } from "@angular/core"; @Component({ moduleId: module.id,selector: "nebula-app",styleUrls: ["./app.component.css"],templateUrl: "./app.component.html",}) export class AppComponent { }
app.component.html:
<h1>hello world!</h1>
app.component.css:
h1{ color: blue; }
只有最后的期望才会失败.它将h1.nativeElement.style.color视为空.好像它没有以某种方式加载CSS.如果我在html中将样式设置为线条样式,则此测试将通过.但是将它作为外部css将会失败.
我究竟做错了什么?我的假设是错误的,compileComponents应该加载外部CSS并将其作为nativeElement的样式?
@R_502_323@
h1.nativeElement.style仅包含在元素上显式设置的样式.例如,以下元素将具有backgroundColorset为红色的样式对象
<h1 style="background-color: red;">hello world!</h1>
您可以使用量角器e2e测试对其进行测试,而不是使用颜色的单元测试.你可以写一个这样的测试:
expect(element(by.css('h1')).getCssValue('color')).toEqual('rgba(0,255,1)');
量角器e2e测试内置于angular-cli生成的Angular2项目中.使用命令ng e2e运行它们