简体   繁体   中英

Override component in another module in Angular TestBed

I'm writing TestBed unit tests.

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(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.

I was also experimenting with overrideModule , without success:

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 ?

The TestBed#overrideComponent method will help you to replace template of any component within TestBed. If it's not enough, use TestBed#overrideModule to replace the whole component (template and class).

Docs are loose: 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

Tests may help too: https://github.com/angular/angular/blob/master/packages/platform-browser/test/testing_public_spec.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM