Suppose i have a service named testService with a function getData in it. Also i have a component ( say A ) into which the service is injected.
export class A implements OnInit,OnDestroy{
saveObj;
constructor(public service:testService){
}
ngOnDestroy(){
if(this.saveObj) this.saveObj.unsubscribe();
}
ngOnInit(){
this.saveObj = this.service.getData.subscribe(res => {
this.func(res);
},
err => {
console.log("Error Occured");
this.saveObj.unsubscribe();
});
}
private func(result: any){
// Some code
}
}
Now i am doing unit testing for this component. The problem is in some cases , it throws an error:
Uncaught TypeError: _this.saveObj.unsubscribe is not a function thrown
Code snippet of spec.ts:
// testServiceStub is just a mock of testService.
beforeEach(async(()=>{
testServiceStub = jasmine.createSpyObj(['getData']);
TestBed.configureTestingModule({
declarations : [A],
schemas : [NO_ERRORS_SCHEMA],
providers : [
{ provide : testService, useValue: testServiceStub }
]
}).compileComponents();
}))
beforeEach(async(()=>{
fixture = TestBed.createComponent(A);
component = fixture.componentInstance;
}))
it('checks whether error is handled or not',()=>{
spyOn(console,'log');
testServiceStub.getData.and.returnValue(throwError({status:404}));
fixture.detectChanges();
expect(console.log).toHaveBeenCalled(); // shows the TypeError
})
it('checks whether value is handled or not',()=>{
testServiceStub.getData.and.returnValue(of(mockData)); // some mock data
fixture.detectChanges();
expect(component.func).toHaveBeenCalled(); // also shows the TypeError
})
I also referred this link unsubscribe is not a function on an observable . But the problem is it also works in some cases and no error is shown.
Please help me figure out the reason and possible scenarios.
UPD: Added onDestroy lifecycle hook