angular - 在 Angular TestBed 的另一个模块中覆盖组件

标签 angular unit-testing karma-jasmine testbed

我正在编写 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/aio/content/examples/testing/src/app/app.component.spec.ts#L74

测试也可能有帮助: 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/

相关文章:

node.js - 使用 Fastify 和 Nestjs 上传文件错误

javascript - 类型错误 : modules[moduleId] is undefined

angular - 在 Angular 中设置全局时区

angular - 错误 : 422 (Unprocessable Entity). Angular4

Angular 6 ngFor按键分组的表列表

matlab - Matlab 工具箱测试中的 stub

unit-testing - 如何等待服务器启动并从 Jenkins/Hudson 运行单元测试

android - 如何使用 mock() 和 spy() 测试静态方法

unit-testing - 在 Angular 6 中运行 ng 测试时出现 null 'appendchild' 错误

未创建 Angular 4 代码覆盖文件夹