2016-11-25 3 views
5

現在、ホストコンポーネントからの入力を受け付け、以下のコードのようなngOnInitライフサイクルフック内で使用される子コンポーネントをテストしようとしています。 ChildComponentがmyValueは、アサーションのためChildComponent.transformedValueへのアクセス権を持つことが可能でありながら、作成時に存在する必要があり、この場合にテストする必要がありますどのように角2 - ngOnInitライフサイクルフックで使用される@inputを使用してコンポーネントをテストする

@Component({ 
    selector: 'my-child-component', 
    template: '<div></div>' 
}) 
class ChildComponent implements OnInit { 
    @Input() myValue: MyObject; 
    transformedValue: SomeOtherObject; 

    ngOnInit():void { 
     // Do some data transform requiring myValue 
     transformedValue = ...; 
    } 
} 

@Component({ 
    template:`<my-child-component [myValue]="someValue"></my-child-component>` 
}) 
class HostComponent { 
    someValue: MyObject = new MyObject(); // how it is initialized it is not important. 
} 

私はngOnInitはすでに、私はまた、作成しようとした

fixture.componentInstance.myValue = someValue; 

を呼び出す時点まで呼ばれていたであろうが、この

componentFixture = testBed.createComponent(LoginFormComponent) 

のような角度テストベッドのクラスを使用してChildComponentを作成してみました私がChildComponent.transformedValueフィールドでアサーションを実行するために必要な、作成されたChildComponentインスタンスへのアクセスを取得するのに苦労しました。

お願いします。

ありがとうございます!

+1

それは' ngOnChanges'のライフサイクルをトリガしますます。http://stackoverflow.com/questions/37408801/testing-ngonchanges-lifecycle-フックイン角度2 – echonax

+1

返信いただきありがとうございます!実際、答えは、テストコンポーネントから子コンポーネントへのアクセスをどのように管理したかについて、以下に投稿した答えとまったく同じです。共有してくれてありがとう! :) –

答えて

2

Angularは、@ViewChild()デコレータを使用して、子コンポーネントを親コンポーネントに挿入する機能を提供します。 "の主張を作り、それはその子コンポーネントインスタンス(およびその変数)を公開し、次の

@Component({ 
    template:`<my-child-component [myValue]="someValue"></my-child-component>` 
}) 
class TestHostComponent { 
    @ViewChild(MyChildComponent) 
    childComponent: MyChildComponent; 
} 

にTestHostcomponent(それは.spec.ts・ファイル中に記述された)を更新することによってhttps://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child

を参照してください。以下のように、「transformedValue」が可能です。あなたは `@ Input`値を変更した場合は、この質問は役に立つかもしれないので

componentFixture = testBed.createComponent(TestHostComponent) 
expect(componentFixture.componentInstance.childComponent.transformedValue).toEqual(...someValue); 
関連する問題