3

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
           */
        });
    })));

  });
4

1 回答 1

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
           */
        });
    })));

  });

我希望这个能帮上忙 :)

于 2016-06-11T16:01:59.120 回答