【发布时间】:2016-11-04 21:24:11
【问题描述】:
我正在尝试创建一个对其进行测试的组件。该组件具有我要测试的外部 CSS。我认为我做的一切都是正确的,但我无法通过考试。这是我的代码: 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 的样式是错误的吗?
【问题讨论】:
-
颜色和背景颜色不同
-
@jonrsharpe 我的例子不好。我会编辑它,但还是不行
-
你能比“不工作”更具体吗?
-
@jonrsharpe 最后一个期望会抛出一个错误,因为它认为 h1.nativeElement.style.color 为空。如果我将样式设置为内联样式,它将起作用,但是将其放在外部 css 文件中会导致并清空 nativelement.style
-
一个错误,还是一个失败的期望?你能edit 提供这些信息吗?
标签: testing angular typescript karma-jasmine