2017-09-22 4 views
2

私はジャスミンに次のコードを持っている:Angular2でdetectChanges()を正しく実装するにはどうすればよいですか?

it('should pass on writing secondvalue in the input', async(() => { 

     const fixture=TestBed.createComponent(AppComponent); 
     const app=fixture.debugElement.nativeElement.querySelector("input").getAttribute("value"); 
     expect(app).toContain("firstvalue"); 
     fixture.detectChanges(); 
     expect(app).toContain("secondvalue"); 

     })); 

問題は、すぐに私がテストを実行すると、テストは失敗したということです。私はそれがdetectChanges()のために待つことを期待しますが、それはしません。

正しく実装するには:入力の2番目の値の入力を待機し、値が "secondvalue"になるかどうかを確認します。

fixture.detectChanges()は、誰かが書き込みを開始したときに入力がトリガーされるのを待つなど、偶数ブロッカーのように動作しませんか?

答えて

2

コンポーネントの状態を変更すると、detectChangesが実行され、変更が反映されます。

例えば、

pageTitle: string; 
ngOnInit() { 
    this.pageTitle = 'first title'; 
} 

、テンプレートに:テストで

<h2>{{pageTitle}}</h2> 

const fixture = TestBed.createComponent(AppComponent); 
const h4 = fixture.debugElement.query(By.css('h4')); 

console.log(component.pageTitle); // 'first title' 
console.log(h4.nativeElement.textContent); // '' 
fixture.detectChanges(); // Propagates ngOnInit changes 
console.log(h4.nativeElement.textContent); // 'first title' 

component.pageTitle = 'second title'; // Here we change state 
console.log(component.pageTitle); // 'second title' 
console.log(h4.nativeElement.textContent); // 'first title' 
fixture.detectChanges(); // Propagate changes 
console.log(h4.nativeElement.textContent); // 'second title' 

典型的なユースケースは次のように、状態に依存事をチェックしていますテンプレートあり:

コンポーネントで

:テストで

over18: boolean = false; 

:私はコンポーネントのロジックをテストしてい

it('should show restricted content if over 18',() => { 
    component.over18 = true; // change state from the default one 
    fixture.detectChanges(); // propagate changes to view 

    // now we can actually test 
    const divElem = fixture.debugElement.query(By.css('div#xxx')); // would be null if not shown in DOM 
    expect(divElem).toBeTruthy(); 
}); 

注意。私の意見では、値が更新される入力に "asdf"と入力すると、ユニットテストの範囲外であることを確認します。この機能はHTML標準/ Angularチームによって提供されています。

+0

新しい値を明示的に指定する必要がありますか?それはカルマ・ランナーからのインプットの中に置くことができますか? – masterach

+0

@masterach値をテストする前に、おそらく 'fixture.detectChanges()'を呼び出す必要があります。また、それはあまり明確ではなく、コンポーネントがどのように見えているのか、そこでは値がどのように変更されていますか。 – hlfrmn

関連する問題