Angular2/testing: 如何运行 测试模拟服务提供商?

Angular2/testing: how to run test with mock service provider?

A​​ngular2 测试

我想 运行 我的组件使用模拟服务,而不是实际服务。 我在beforeEachProviders中提供了模拟服务(MockMyService),它仍然在调用实际服务。

describe('List view component', () => {

  beforeEachProviders(() => {
    return [
      ROUTER_PROVIDERS,
      HTTP_PROVIDERS,
      provide(RouteParams, { useValue: new RouteParams({ query: 'test' }) }),
      provide(MyService, { useClass: MockMyService }),
      MyComponent,
      provide(APP_BASE_HREF, { useValue: '/' }),
      provide(ROUTER_PRIMARY_COMPONENT, { useValue: AppComponent }),
      provide(ApplicationRef, { useClass: MockApplicationRef })
    ];
  });

  it('1: component value check',
      async(inject([TestComponentBuilder, MyComponent], (tcb: TestComponentBuilder, myComponent) => {
        return tcb.createAsync(MyComponent).then((fixture) => {
          fixture.detectChanges();
          /**
           * my custom stuff
           */
        });
    })));

  });

您还可以覆盖 TestComponentBuilder 本身的提供商。

解决方法如下: (刚刚覆盖 tcb 中的服务)

describe('List view component', () => {

  beforeEachProviders(() => {
    return [
      ROUTER_PROVIDERS,
      HTTP_PROVIDERS,
      { provide: RouteParams, useValue: new RouteParams({ query: 'test' }) },
      { provide: MyService, useClass: MockMyService },
      MyComponent,
      { provide: APP_BASE_HREF, useValue: '/' }),
      { provide: ROUTER_PRIMARY_COMPONENT, useValue: AppComponent }),
      { provide: ApplicationRef, useClass: MockApplicationRef })
    ];
  });

  it('1: component value check',
      async(inject([TestComponentBuilder, MyComponent], (tcb: TestComponentBuilder, myComponent) => {
        return tcb.overrideProviders(MyComponent, [
          { provide: MyService, useClass: MockMyService }
        ]).createAsync(MyComponent).then((fixture) => {
          fixture.detectChanges();
          /**
           * my custom stuff
           */
        });
    })));

  });

我希望这会有所帮助:)