2017-09-23 9 views
0

私は次のコードを持っている:かかわらずfixture.detectChanges() "新" の値にelement1.textContent()変更のなぜangular2にdetectChangesが必要なのですか?

it ("test detect change", async()=>{ 
    let fixture= TestBed.createComponent(AppComponent); 
    let element1= fixture.debugElement.nativeElement.querySelector("h1"); 
    expect(element1.textContent).toContain("come"); 
    element1.textContent="new"; 
    //fixture.detectChanges(); 
    expect(element1.textContent).toContain("come"); 
}); 

を?私がdetectChanges()関数を呼び出した場合にのみ変更が行われるべきではありませんか?さもなければ、変更が関数が呼び出されることなく登録されているので、とにかくdetectChangesを持つ点は何ですか?

基本的に私は変化が原因あなたがテストしていないdetectChanges機能

答えて

1

を呼び出していないのelement1.textContent =「新しい」に登録されていてはいけないので、私の最後の機能は、テストに合格することを期待期待しますあなたのコンポーネントを正しく。フィクスチャの内容を変更することはできません。コンポーネントのプロパティを変更し、それに応じてフィクスチャーが変更されたかどうかを確認したい場合は、detectChanges()メソッドが必要です。

例:

app.component.ts

@Component({ 
    selector : 'app-root', 
    template: '<h1>{{ title }}</h1>', 
}) 
export class AppComponent { 
    title = 'Test'; 
} 

app.component.spec.ts

it('should change the title',() => { 
    const compiled = fixture.debugElement.nativeElement; 
    const component = fixture.componentInstance; 

    expect(compiled.querySelector('h1').textContent).toBe('Test'); 
    component.title = 'New'; 
    fixture.detectChanges(); // <- Required for the following expectation to pass 
    expect(compiled.querySelector('h1').textContent).toBe('New'); 
}); 

あなたの質問に直接答えるには、コンポーネント内で起こった変更を検出してフィクスチャを再レンダリングするために、フィクスチャdetectChanges()メソッドが必要です。

+1

私はそう考えていましたが、回答はtnxでした。 – masterach

+0

問題ありません。私はあなたを助けることができてうれしいです。 – Mihailo

関連する問題