I am running into an issue of trying to spy on a service function call that gets called in the constructor. The test is basic, just verifying that the function call actually gets called.
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
providers: [TestService]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
let service = fixture.debugElement.injector.get(TestService);
component = fixture.componentInstance;
spyOn(service , "start").and.callThrough();
fixture.detectChanges();
});
it('start gets called', () => {
expect(service .start).toHaveBeenCalled();
})
As for AppComponent , in the constructor it is simply calling service.start() What I think the issue is that the spyOn gets called after the component is created but how would I spy on the service before injecting it? ie:
fixture = TestBed.createComponent(AppComponent);
let service = fixture.debugElement.injector.get(TestService);
It seems to me the component's constructor has been called by the time you set up the spy, so need to change the sequence a bit.
beforeEach(() => {
let service = TestBed.get(TestService);
spyOn(service , "start").and.callThrough();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
Ref Angular Test Bed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With