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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…