Angular 2 - 在依赖于其他服务的组件中模拟服务

xio*_*tee 1 unit-testing karma-jasmine angular

如何模拟依赖于组件中的另一个服务的服务?请检查下面的代码。

a.component.ts

@Component({
  selector: 'my-comp',
  templateUrl: './my.component.html',
  providers: [ MyServiceA ]
})
export class MyComponent {
Run Code Online (Sandbox Code Playgroud)

我的服务-a.service.ts

@Injectable()
export class MyServiceA{
  constructor(private myServiceB: MyServiceB) {}
Run Code Online (Sandbox Code Playgroud)

我的服务-b.service.ts

export class MyServiceB{
constructor(private myServiceC: MyServiceC,
              private myServiceD: MyServiceD) {}
Run Code Online (Sandbox Code Playgroud)

如何在 TestBed 配置中模拟a.component.spec.ts中的服务?请帮忙。谢谢你。

Pau*_*tha 5

你可以随意模拟它。其他服务无所谓。我想也许您面临的问题是@Component.providers. 使用它,您在 中配置的任何模拟TestBed都不会被用作@Component.providers优先级,从而导致 Angular 尝试创建它,而不是使用模拟。

为了解决这个问题,Angular 提供了TestBed.overrideComponent方法,这样我们就可以覆盖诸如模板和提供者之类的东西@Component

beforeEach(() => {
  let myMockService = new MyMockService();

  TestBed.configureTestingModule({
    providers: [
      // the following will not be used
      { provide: MyService, useValue: myMockService }
    ]
  });
  TestBed.overrideComponent(MyComponent, {
    set: {
      providers: [
        // this will override the @Component.providers:[MyService]
        { provide: MyService, useValue: myMockService }
      ]
    }
  });
})
Run Code Online (Sandbox Code Playgroud)