2017-09-29 3 views
0

親コンポーネント:親コンポーネントのプロパティをチェックするテストケースを書くには?

export class PlayerListComponent { 
    flag = false; 
} 

子コンポーネント:

export class PlayerAddComponent { 
    @Output() notifyParent: EventEmitter<any> = new EventEmitter(); 

    clkCancle() { 
    this.notifyParent.emit(false); 
    // this will set parent component property 'flag' to false. 
    } 
} 

今、私はジャスミンのspecファイルでテストケースを書くことができますか?二つの成分を一緒にテストするには

it('cancel button click should set flag to false', function() { 
    // Act 
    component.clkCancle(); 

    // Assert 
    // Since component do not have flag property. It will be set in parent while by Emitter. 
    expect(???).toBe(false); 
}); 
+0

* "これは、親コンポーネントのプロパティ 'flag'をfalseに設定します* *いいえ、それは*子の*仕事ではありません。子供はちょうど発射します、あなたは子供のユニットテストでテストすることができます。必要に応じて対応するのは*親*の責任です。 2つのコンポーネントを一緒にテストしたい場合は、 'TestBed'で*両方を宣言し、親をインスタンス化します。 – jonrsharpe

+0

テストで、 ''のようなテンプレートを持つコンポーネントを作成し、キャンセルボタンをクリックするとコンポーネントのフラグが確かにテストされますfalseに設定します。また、親とその子の統合をテストする場合は、テストで実際の親コンポーネントを使用します。 –

+0

私は、子コンポーネント用のスペックファイルを作成し、それをバインドするために親コンポーネントにhtml以下で使用しました。

答えて

-2

、あなたは同じTestBedの両方でロードする必要があります。例えば:それはそれの結果として何が起こるのか、子供の責任の一部であってはならないので、

describe('component interaction',() => { 
    let fixture: ComponentFixture<PlayerListComponent>; 
    let component: PlayerListComponent; 

    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     declarations: [PlayerListComponent, PlayerAddComponent], 
    }).compileComponents(); 
    })); 

    beforeEach(() => { 
    fixture = TestBed.createComponent(PlayerListComponent); 
    component = fixture.componentInstance; 
    fixture.detectChanges(); 
    }); 

    it('should set the parent flag when the child method is called',() => { 
    // Arrange 
    const child: PlayerAddComponent = fixture.debugElement 
     .query(By.directive(PlayerAddComponent)) 
     .componentInstance; 

    // Act 
    child.clkCancle(); // ...Cancel? 
    fixture.detectChanges(); 

    // Assert 
    expect(component.flag).toBe(false, 'parent flag should be set'); 
    } 
}); 

そうしないと、あなただけ(この動作はなしに変更される可能性が、子どもが適切なタイミングで放出することをテストする必要があります子供が)変更、または子が使用されている場所に応じて異なる場合がされている:

it('should emit when the method is called', done => { 
    component.clkCancle(); // here component is PlayerAddComponent 

    component.notifyParent.subscribe(flag => { 
    expect(flag).toBe(false, 'should emit false'); 
    done(); 
    }); 
}); 

注両方のケースで、私は例えばを使用して、あなたはボタンをクリックしたときに、これは起こることをテストをお勧めします、ということfixture.nativeElement.querySelector('...').click();ではなく、メソッドが呼び出されたとき。 の動作の実装を分離するのに役立ちます。これにより、テストを更新せずに内部メソッドの名前を変更することができます。

関連する問題