Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading external css in Angular 2 and testing it

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?

like image 978
user3521794 Avatar asked Nov 04 '16 21:11

user3521794


2 Answers

h1.nativeElement.style only contains styles set explicitly on the element. For example, the following element will have a style object with backgroundColorset 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

like image 66
Klas Mellbourn Avatar answered Oct 10 '22 04:10

Klas Mellbourn


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)');
like image 32
István Békési Avatar answered Oct 10 '22 05:10

István Békési