Override component in another module in Angular TestBed
Asked Answered
L

1

7

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?

Lareine answered 10/11, 2017 at 14:4 Comment(1)
Would it be possible to have a plunker or some workable example? Would be happy to debug it, but it's difficult to know the exact problem as is.Flange
A
10

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

Absorber answered 5/4, 2018 at 12:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.