[英]Angular 2 - testing a component with @input used in ngOnInit lifecycle hook
Currently I am trying to test a child component which is accepting an input from the host component, and used within the ngOnInit life cycle hook like the code below. 目前我正在尝试测试一个子组件,它接受来自主机组件的输入,并在ngOnInit生命周期钩子中使用,如下面的代码。
@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.
}
How should the ChildComponent be tested in this case where myValue needs the to be present upon creation while being able to have access to ChildComponent.transformedValue for assertion. 在这种情况下,应该如何测试ChildComponent,其中myValue需要在创建时出现,同时能够访问ChildComponent.transformedValue以进行断言。
I tried creating the ChildComponent using the Angular TestBed class like this 我尝试使用像这样的Angular TestBed类创建ChildComponent
componentFixture = testBed.createComponent(LoginFormComponent)
however the ngOnInit would have already been called up to the point where I call 但是ngOnInit已经调到我打电话的地步
fixture.componentInstance.myValue = someValue;
I also tried creating a fixture of the HostComponent, and while that works, I got stuck at getting access to the ChildComponent instance that was created, which i require to perform assertions on the ChildComponent.transformedValue field. 我也尝试创建HostComponent的一个fixture,虽然这有效,但我仍然无法访问创建的ChildComponent实例,我需要在ChildComponent.transformedValue字段上执行断言。
Help is greatly appreciated! 非常感谢帮助!
Thanks a lot! 非常感谢!
Angular offers the ability to inject children components to their parent components using the @ViewChild() decorator. Angular提供了使用@ViewChild()装饰器将子组件注入其父组件的功能。 See https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child 请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child
By updating the TestHostcomponent (that is written within the .spec.ts file) to the following 通过将TestHostcomponent(在.spec.ts文件中写入)更新为以下内容
@Component({
template:`<my-child-component [myValue]="someValue"></my-child-component>`
})
class TestHostComponent {
@ViewChild(MyChildComponent)
childComponent: MyChildComponent;
}
it exposes its child component instance ( and its variables ), making the assertion of the 'transformedValue' possible, as per below. 它暴露了它的子组件实例(及其变量),使得'transformedValue'的断言成为可能,如下所示。
componentFixture = testBed.createComponent(TestHostComponent)
expect(componentFixture.componentInstance.childComponent.transformedValue).toEqual(...someValue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.