且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在单元测试期间模拟angular2中的自定义服务

更新时间:2023-02-14 17:32:10

是因为这个原因

@Component({
  providers: [PonyService]  <======
})

这使得服务范围仅限于组件,这意味着Angular将为每个组件创建它,也意味着它将取代在模块级别配置的所有全局提供程序.这包括您在测试台中配置的模拟提供程序.

This makes it so that the service is scoped to the component, which means that Angular will create it for each component, and also means that it supercedes any global providers configured at the module level. This includes the mock provider that you configure in the test bed.

要解决此问题,Angular提供了TestBed.overrideComponent方法,该方法允许我们覆盖@Component.providers@Component.template之类的东西.

To get around this, Angular provides the TestBed.overrideComponent method, which allows us to override things like the @Component.providers and @Component.template.

TestBed.configureTestingModule({
  declarations: [PoniesComponent, PonyComponent]
})
.overrideComponent(PoniesComponent, {
  set: {
    providers: [
      {provide: PonyService, useClass: MockPonyService}
    ]
  }
});