[英]Angular2 @Viewchild unit test
I have a component like this: 我有一个像这样的组件:
export class ParentComponent implements OnInit, OnDestroy {
@ViewChild(ChildComponent) childComponent: ChildComponent;
}
which is using the childComponent
to make a call, let's say like this: 这是使用childComponent
进行调用的,我们这样说:
this.childComponent.method();
within ParentComponent
method. 在ParentComponent
方法中。
So, when I am trying to test the ParentComponent
method which is internally using the ChildComponent
, the childComponent is returning as undefined. 因此,当我尝试测试内部使用ChildComponent
的ParentComponent
方法时,childComponent返回未定义状态。
How to resolve the issue? 该如何解决?
Declare fixture for child component inside describe. 为内部子组件声明夹具描述。
let childFixture: ComponentFixture<childComponent>;
And now create component instance using 现在使用创建组件实例
let childComp = childFixture.componentInstance;
In most cases when you want to use ViewChild in your test, just add it to the your test decleration like this : 在大多数情况下,当您想在测试中使用ViewChild时,只需将其添加到测试库中,如下所示:
beforeEach(async(() => {
TestBed
.configureTestingModule({
imports: [],
declarations: [ChildComponent],
providers: [],
})
.compileComponents()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.