Search code examples
angularangular2-testing

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


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

  });

Solution

  • 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 :)