Angular2 / testing:如何使用模拟服务提供程序运行测试?

时间:2016-06-11 15:55:46

标签: angular angular2-testing

Angular2测试

我想使用模拟服务运行我的组件,而不是实际的服务。 我在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
           */
        });
    })));

  });

1 个答案:

答案 0 :(得分:3)

您还可以覆盖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
           */
        });
    })));

  });

我希望,这会有所帮助:)