2016-11-30 18 views
2

OnPush変更検出ストラテジでコンポーネントをテストする際に問題があります。角度2のOnPushコンポーネントのテスト

テストは、私はそれが期待どおりに動作Default戦略を使用している場合、この

it('should show edit button for featured only for owners',() => { 
    let selector = '.edit-button'; 

    component.isOwner = false; 
    fixture.detectChanges(); 

    expect(fixture.debugElement.query(By.css(selector))).toBeFalsy(); 

    component.isOwner = true; 
    fixture.detectChanges(); 

    expect(fixture.debugElement.query(By.css(selector))).toBeTruthy(); 
}); 

のようになりますが、OnPushisOwnerへの変更はdetectChangesへの呼び出しによって再レンダリングされていません。何か不足していますか?

+1

このスレッドを見てくださいhttps://github.com/angular/angular/issues/12313ここであなたのテストはhttps://plnkr.co/edit/llJG17sBZZUXXBertYPp?p=preview – yurzui

答えて

1

あなたはギュンターの答えangular 2 change detection and ChangeDetectionStrategy.OnPush @この素晴らしいをチェックアウトするなら、あなたは以下のようにイベントハンドラを使用して、それを回避することができます。

const fixture = TestBed.overrideComponent(TestComponent, {set: {host: { "(click)": "dummy" }}}).createComponent(TestComponent); 
// write your test 
fixture.debugElement.triggerEventHandler('click', null); 
fixture.detectChanges(); 

は、ここであなたが入力を変更したこと、角伝える必要がありますPlunker Example

+0

私は解決策を行ったあなたのコメントから。これは "クリーナー"かもしれませんが、もっと面倒です。だから私はヘルパーでハックを包み込み、将来的にはより良い解決策を望んでいます:)ありがとう! – altschuler

0

ですコンポーネントのプロパティ。理想的な世界で、あなたは角(https://github.com/angular/angular/issues/12313)にバグがあるため、動作しないこと、残念ながら

component.isOwner = false; 
fixture.changeDetectorRef.markForCheck(); 
fixture.detectChanges(); 

component.isOwner = false; 
fixture.detectChanges(); 

を置き換えます。ここに記載されている回避策の1つを使用できます。

関連する問題