Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 test spec for a component that provides a service

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?

like image 454
Sefi Ninio Avatar asked Oct 06 '16 10:10

Sefi Ninio


People also ask

How do you inject a service in Spec TS?

For inject a service into spec file, you have to add TestBed configuration and register your service in provider array same as module ts file. Show activity on this post. This answer assumes you want to unit test the component.


1 Answers

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:

  • Override Component Providers
like image 152
Paul Samsotha Avatar answered Sep 22 '22 22:09

Paul Samsotha