【发布时间】:2016-11-25 08:25:35
【问题描述】:
目前我正在尝试测试一个子组件,该子组件接受来自主机组件的输入,并在 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.
}
在 myValue 需要在创建时存在同时能够访问 ChildComponent.transformedValue 进行断言的这种情况下,应如何测试 ChildComponent。
我尝试像这样使用 Angular TestBed 类创建 ChildComponent
componentFixture = testBed.createComponent(LoginFormComponent)
但是 ngOnInit 已经被调用到我调用的位置
fixture.componentInstance.myValue = someValue;
我还尝试创建 HostComponent 的固定装置,虽然它有效,但我无法访问已创建的 ChildComponent 实例,我需要在 ChildComponent.transformedValue 字段上执行断言。
非常感谢您的帮助!
非常感谢!
【问题讨论】:
-
如果您更改
@Input值,它将触发ngOnChanges生命周期,所以这个问题可能有用:stackoverflow.com/questions/37408801/… -
感谢您的回复!事实上,给出的答案与我在下面发布的关于我如何设法从测试组件访问子组件的答案完全相同。不过感谢分享! :)
标签: javascript angular testbed