2016-11-25 42 views
5

當前我正在測試一個接受來自主機組件的輸入並在ngOnInit生命週期鉤子內使用的子組件,如下面的代碼。Angular 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. 
} 

應如何ChildComponent在這種情況下myvalue的需要是存在於創作,同時能夠有機會獲得ChildComponent.transformedValue的斷言進行測試。

我嘗試使用角度測試牀類這樣

componentFixture = testBed.createComponent(LoginFormComponent) 

然而ngOnInit就已經叫了起來,我叫

fixture.componentInstance.myValue = someValue; 

我也嘗試創建一個點創建ChildComponent HostComponent的夾具,雖然這工作,我被困在獲得創建的ChildComponent實例,我需要執行斷言ChildComponent.transformedValue字段。

非常感謝幫助!

非常感謝!

+1

如果你改變了'@ Input'值時,會觸發'ngOnChanges'生命週期,因此這個問題可能是有用的:HTTP://stackoverflow.com/questions/37408801/testing-ngonchanges-lifecycle- hook-in-angular-2 – echonax

+1

感謝您的回覆!事實上,給出的答案與我在下面發佈的有關如何設法從測試組件訪問子組件的答案完全相同。感謝分享! :) –

回答

2

Angular提供了使用@ViewChild()裝飾器將子組件注入其父組件的功能。見https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child

通過更新TestHostcomponent(即在.spec.ts文件中寫入)以下

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

它暴露了它的子組件實例(及其變量),使得斷言的「轉化價值'可能,如下所示。

componentFixture = testBed.createComponent(TestHostComponent) 
expect(componentFixture.componentInstance.childComponent.transformedValue).toEqual(...someValue); 
相關問題