我有一个使用ChildComponentA作为@ViewChild的MainComponent。MainComponent正在调用ChildComponentA上的方法。
我想写一个模拟ChildComponentA的单元测试用例。如何使用TestBed (在Angular 2 RC5中)做到这一点?
在我使用overrideDirective(MainComponentName, ChildComponentA, MockChildComponentA);之前,有没有使用TestBed的等价物
我试着用
TestBed.overrideComponent(ChildComponentA,{
set: {
template: '<div></div>'
}
}); 它只是设置模板,但我也想模拟组件中的方法。
发布于 2016-09-07 19:08:33
我认为在这种情况下,您可以尝试使用模拟组件来替换子组件。只需创建一个具有相同选择器的模拟组件,并使用TestBed删除实际子组件的声明,然后将该声明添加到模拟组件中。
@Component({
selector: 'child',
template: '<div></div>'
})
class MockComponent {
}在您的测试中,执行此操作以使用模拟组件:
TestBed.configureTestingModule({
imports: [MyModule],
declarations: [ParentComponent, MockComponent]
});
TestBed.overrideModule(MyModule, {
remove: {
declarations: [ParentComponent, ChildComponent],
exports: [ParentComponent, ChildComponent]
}
});更多细节在这里:https://github.com/angular/angular/issues/10689。请确保重新声明ParentComponent,否则它将无法工作(不确定原因)。
如果使用@ViewChild获取对子组件的引用,则需要将其修改为不使用组件的类型,而是使用id。使用@ViewChild('child')而不是@ViewChild(ChildComponent)。请参阅此处的第二个示例:http://learnangular2.com/viewChild/
发布于 2019-09-05 05:55:54
请注意,如果ChildComponent是在TestModule本身中声明的,则不需要覆盖声明原始模块的模块。
因此,如果您的TestBed声明如下所示:
TestBed.configureTestingModule({
declarations: [
ParentComponent,
ChildComponent // This is what you'd like to mock
]
});然后,要覆盖ChildComponent,您只需要:
@Component({
selector: 'child',
template: '<div></div>'
})
class MockChildComponent {
}
TestBed.configureTestingModule({
declarations: [
ParentComponent,
MockChildComponent // Notice the original is replaced by the mock
]
});只要ChildComponent和MockChildComponent有相同的选择器,这个选择器就可以工作。
对此问题给出的另一个答案适用于将ChildComponent从不同模块引入TestBed的情况。
备注
如果您的ChildComponent有任何@Input或@Output,那么在您的MockChildComponent中也要包含它们。
https://stackoverflow.com/questions/39281848
复制相似问题