6

我正在编写 TestBed 单元测试。

有某个组件,它是被测组件的子组件。该子组件在测试运行时会导致错误。该子组件与测试本身无关;它只是造成问题。

我想用一个假人替换它,或者阻止它被添加。

有问题的组件来自被测组件模块以外的模块

我试图制作一个存根/虚拟对象:

@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

4

1 回答 1

9

TestBed#overrideComponent方法将帮助您替换 TestBed 中任何组件的模板。如果还不够,请使用TestBed#overrideModule替换整个组件(模板和类)。

文档很松散:https ://angular.io/api/core/testing/TestBed

但示例更有帮助: 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/packages/platform-b​​rowser/test/testing_public_spec.ts

于 2018-04-05T12:26:09.233 回答