2016-11-04 31 views
4

我正在嘗試爲它創建一個組件。該組件具有我想測試的外部CSS。我認爲我做的都是對的,但我無法通過測試。這裏是我的代碼: app.component.spec.ts在Angular 2中加載外部css並測試它

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; 
} 

只有l預計會失敗。它將h1.nativeElement.style.color視爲空。好像它沒有以某種方式加載CSS。如果我在HTML中將線型放入線樣式,則此測試將通過。但把它作爲一個外部的CSS將會失敗。

我在做什麼錯?我的假設是錯誤的,compileComponents應該加載外部CSS並將其作爲nativeElement的樣式?

+0

顏色與背景顏色不同 – jonrsharpe

+0

@jonrsharpe我的例子不好。我會編輯它,但仍然不起作用 – user3521794

+0

你能比*「不起作用」*更具體嗎? – jonrsharpe

回答

3

h1.nativeElement.style只包含明確設置元素的樣式。例如,下面的元素將與backgroundColor設置的樣式對象red

<h1 style="background-color: red;">hello world!</h1> 

而不是使用單元測試的顏色,你可以用量角器端對端測試測試。在那裏,你可以寫這樣一個測試:

expect(element(by.css('h1')).getCssValue('color')).toEqual('rgba(0, 0, 255, 1)'); 

量角器端對端測試中內置了由angular-cli產生Angular2項目。你用命令運行它們ng e2e

+0

所以這就是原因。是的,我把它改爲量角器,它工作。但我有一個問題。這是爲什麼? – user3521794

+1

@ user3521794很好的問題。我不確定。也許他們這樣看待:應用程序的外觀和感覺不屬於單元測試,而更自然地是集成測試整個應用程序的一部分,其中所有元素都顯示並受到所有CSS圖表(包括全局圖表)的影響。所以這就是爲什麼他們在e2e中創建了測試css的功能。 –

0

不知道這是否是一種好的做法,但可以測試計算式樣。 改變你的最後除了這樣的事情應該工作,雖然:

expect(window.getComputedStyle(h1.nativeElement).color).toBe('rgb(0, 0, 255)');