我正在编写 TestBed 单元测试。
有一个特定的组件,它是被测组件的子组件。该子组件在测试运行时会导致错误。该子组件与测试本身无关;这只会引起问题。
我想用一个虚拟的替换它,或者阻止它被添加。
有问题的组件来自被测组件模块的其他模块。
我试图制作一个 stub /虚拟:
@Component({
selector : 'problematic-component-selector',
template : 'FAKE CAPTCHA',
})
export class ProblematicComponentStubComponent {
}
这是我的beforeEach
:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
ReactiveFormsModule,
FormsModule,
RouterModule,
ModuleOfProblematicComponent,
],
declarations: [
ComponentUnderTest,
ProblematicComponentStubComponent, /* NOTE: here I tried to declare the fake one */
],
providers: [
{ provide: Router, useClass: RouterStub },
{ provide: ActivatedRoute, useClass: Stub },
],
我试图覆盖组件模板,以防止错误:
TestBed.overrideComponent(ProblematicComponent, {
set: {
template: 'Fake Captcha' // prevent ReCaptcha error
}
})
我知道 NO_ERRORS_SCHEMA
,但没有帮助。
我也在试验 overrideModule
,但没有成功:
TestBed.overrideModule(ModuleOfProblematicComponent, {
remove: {
declarations: [ProblematicComponent],
},
add: {
declarations: [ProblematicComponentStubComponent],
}
});
因此,问题是:是否可以覆盖 ProblematicComponent
(它位于 ComponentUnderTest
模块以外的模块中?
最佳答案
TestBed#overrideComponent
方法将帮助您替换 TestBed 中任何组件的模板。如果还不够,请使用 TestBed#overrideModule
替换整个组件(模板和类)。
文档松散:https://angular.io/api/core/testing/TestBed
测试也可能有帮助: https://github.com/angular/angular/blob/master/packages/platform-browser/test/testing_public_spec.ts
关于angular - 在 Angular TestBed 的另一个模块中覆盖组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47224526/