19

I am using Angular 2 final (2.0.1). I have a component that provides a service. It is the only one that uses it, this is why it provides it and not the containing module and it is also being injected into the constructor.

@Component({
    selector: 'my-comp',
    templateUrl: 'my-comp.component.html',
    styleUrls: ['my-comp.component.scss'],
    providers: [MyService],
})
export class MyComponent {

    constructor(private myService: MyService) {
    }
}

When I try to implement the spec, it fails.

describe("My Component", () => {

beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [
            {
                provide: MyService,
                useClass: MockMyService
            },
        ]
    });

    this.fixture = TestBed.createComponent(MyComponent);
    this.myService = this.fixture.debugElement.injector.get(MyService);

});

describe("this should pass", () => {

    beforeEach(() => {
        this.myService.data = [];
        this.fixture.detectChanges();
    });

    it("should display", () => {
        expect(this.fixture.nativeElement.innerText).toContain("Health");
    });

});

but, when I move the service provide declaration from the component to the containing module, the tests passes.

I assume it is because the TestBed testing module defines the mock service, but when the component is created - it overrides the mock with the actual implementation...

Does anyone have any idea how to test a component that provides a service and use a mock service?

Sefi Ninio
  • 427
  • 1
  • 5
  • 12

1 Answers1

38

You need to override the @Component.providers, as it has precedence over any mock you provide through the test bed config.

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [MyComponent]
  });

  TestBed.overrideComponent(MyComponent, {
    set: {
      providers: [
        { provide: MyService, useClass: MockMyService }
      ]
    }
  }); 
});

See Also:

developer033
  • 24,267
  • 8
  • 82
  • 108
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • 3
    When coming to this answer I easily overlooked the importance of using fixture.debugElement.injector.get to get the service inside the test, instead of using the TestBed. https://angular.io/guide/testing#the-override-tests – carraua Mar 19 '20 at 18:03