[英]Override component in another module in Angular TestBed
I'm writing TestBed unit tests. 我正在编写TestBed单元测试。
There is a certain component, which is a child of the component-under-test. 有一个组件,它是被测组件的子组件。 That child component causes errors while the test is running.
该子组件在测试运行时会导致错误。 That child component is not relevant to the test itself;
该子组件与测试本身无关; it's just causing problems.
这只是造成问题。
I would like to replace it with a dummy, or prevent it from being added. 我想用假人替换它,或者防止它被添加。
The problematic component is from a module other than the component-under-test's module. 有问题的组分是来自不同于组分被测的模块以外的模块。
I tried to make a stub/dummy: 我试图制作一个存根/假人:
@Component({
selector : 'problematic-component-selector',
template : 'FAKE CAPTCHA',
})
export class ProblematicComponentStubComponent {
}
Here is my beforeEach
: 这是我的
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 },
],
I tried to override the components template, to prevent the errors: 我试图覆盖组件模板,以防止错误:
TestBed.overrideComponent(ProblematicComponent, {
set: {
template: 'Fake Captcha' // prevent ReCaptcha error
}
})
I know about NO_ERRORS_SCHEMA
, but it did not help. 我知道
NO_ERRORS_SCHEMA
,但它没有帮助。
I was also experimenting with overrideModule
, without success: 我也在尝试使用
overrideModule
,但没有成功:
TestBed.overrideModule(ModuleOfProblematicComponent, {
remove: {
declarations: [ProblematicComponent],
},
add: {
declarations: [ProblematicComponentStubComponent],
}
});
So, question is: is it possible to override the ProblematicComponent
(which is in a module other than the module of the ComponentUnderTest
? 所以,问题是:是否有可能覆盖
ProblematicComponent
(它位于ComponentUnderTest
模块以外的模块中?
The TestBed#overrideComponent
method will help you to replace template of any component within TestBed. TestBed#overrideComponent
方法将帮助您替换TestBed中任何组件的模板。 If it's not enough, use TestBed#overrideModule
to replace the whole component (template and class). 如果还不够,请使用
TestBed#overrideModule
替换整个组件(模板和类)。
Docs are loose: https://angular.io/api/core/testing/TestBed 文档是松散的: https : //angular.io/api/core/testing/TestBed
But examples are more helpful: https://github.com/angular/angular/blob/master/aio/content/examples/testing/src/app/app.component.spec.ts#L74 但是示例更有用: https : //github.com/angular/angular/blob/master/aio/content/examples/testing/src/app/app.component.spec.ts#L74
Tests may help too: https://github.com/angular/angular/blob/master/packages/platform-browser/test/testing_public_spec.ts 测试也可能有所帮助: https : //github.com/angular/angular/blob/master/packages/platform-browser/test/testing_public_spec.ts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.