I am trying to create a component with a test for it. The component has external CSSs that I want to test. I think I am doing everything right, but I couldn't make it to pass the test. Here are my code: 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;
}
Only the last expect will fail. It sees h1.nativeElement.style.color as empty. Seems like it didn't load the CSS somehow. If I put the style as in line style in html this test will pass. But having it as an external css will fail the expect.
What am I doing wrong? Is my assumption wrong that the compileComponents should load the external CSS and put it as the style of the nativeElement?
h1.nativeElement.style
only contains styles set explicitly on the element. For example, the following element will have a style object with backgroundColor
set to red
<h1 style="background-color: red;">hello world!</h1>
Instead of using a unit test for the color, you can test it using protractor e2e tests. There you could write a test like this:
expect(element(by.css('h1')).getCssValue('color')).toEqual('rgba(0, 0, 255, 1)');
Protractor e2e tests are built into Angular2 projects generated by angular-cli. You run them with the command ng e2e
Not sure if it's a good practice, but it is possible to test the computed style. Changing your last except to something like this should work though:
expect(window.getComputedStyle(h1.nativeElement).color).toBe('rgb(0, 0, 255)');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With