2016-11-04 11 views
4

私は、テスト用のコンポーネントを作成しようとしています。このコンポーネントには、テストしたい外部CSSがあります。私はすべてを正しくやっていると思いますが、テストに合格することができませんでした。ここでは私のコードです: app.component.spec.ts外部CSSをAngular 2に読み込んでテストする

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のスタイルとして配置するという私の仮定は間違っていますか?

+0

色と背景色は、例の@jonrsharpe私の悪い – jonrsharpe

+0

は異なっています。私はそれを編集しますが、まだ動作しません – user3521794

+0

*「動作しません」*より具体的になりますか? – jonrsharpe

答えて

3

h1.nativeElement.styleには、要素に明示的に設定されたスタイルのみが含まれます。たとえば、以下の要素がred

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

代わりの色のためのユニットテストを使用してbackgroundColorセットでスタイルオブジェクトを持って、あなたは分度器E2Eテストを使用してテストすることができます。そこには、このようなテストを書くことができます:

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

分度器E2Eテストはangular-cliによって生成されたAngular2プロジェクトに組み込まれています。コマンドを使用して実行しますng e2e

+0

それが理由です。はい、私は分度器に変更し、それは働いた。しかし、私は質問があります。何故ですか? – user3521794

+1

@ user3521794良い質問です。よく分かりません。アプリケーションのルック・アンド・フィールは単体テストではなく、すべての要素が表示され、グローバルなものを含むすべてのCSSシートによって影響を受けるアプリケーション全体をテストする統合の一部です。だから、彼らはcssをテストするためにe2eの機能を作ったのです。 –

0

これは良い習慣だとわかりませんが、計算されたスタイルをテストすることは可能です。これはしかし動作するはずのようなものを除いて、あなたの最後を変更 :

expect(window.getComputedStyle(h1.nativeElement).color).toBe('rgb(0, 0, 255)'); 
関連する問題