3

Angular2 testing

I want to run my component with the mock service, not the actual service. I have provided the mock service(MockMyService) in beforeEachProviders, still it is calling the actual service.

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

  });
Community
  • 1
  • 1
Mike
  • 43
  • 1
  • 6

1 Answers1

3

You can also override the providers in TestComponentBuilder itself.

here is the solution: (Just overridden the service in 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
           */
        });
    })));

  });

I hope, this will help :)

Edd
  • 25
  • 4
Brajendra Swain
  • 355
  • 2
  • 8
  • I am glad to hear this :) – Brajendra Swain Jun 15 '16 at 03:56
  • 2
    beforeEachProviders has been replaced by TestBed in RC5. I created a [plunk](https://plnkr.co/edit/dc4pWJ?p=preview) to show a working example of mocking out a service (see hero.service.spec.ts). – Dave Aug 22 '16 at 23:37