I have written a unit test for this function:
getCarsAndSetup(){
this.getCars();
this.getFactoryInfo();
}
This is the getCars() function:
getCars() {
const subscription = this.carDetailsService.getAll().subscribe((carDetails) => {
this.carInfoService.setCars(carDetails);
subscription.unsubscribe(); <-------------- Here the
subscription is undefined
when running the test,
however when running
the app, the subscription
is defined and
everything is fine
});
}
This is the unit test:
fdescribe('getCarsAndSetup', () => {
it('should get cars and set them up', () => {
component.getFactoriesAndUnsubscribe();
spyOn(component, "getCars");
spyOn(component, "getFactoryInfo");
expect(component.getCars).toHaveBeenCalled();
expect(component.getFactoryInfo).toHaveBeenCalled();
});
});
I am using a mock for carDetailsService. This is the getAll() method in the carDetailsService mock:
getAll(): Observable<CarModel[]> {
return Observable.create((observer:any) => {
observer.next([]);
});
}
And this is the same method in the REAL carDetailsService:
getAll(): Observable<CarModel[]> {
return this.http.get<CarModel[]>(this.carUrl);
}
The problem is that when I run the application itself, the subscription in the getCars() method is defined, I can unsubscribe from it etc. and everything is fine.
However when I run the tests, this test fails, because for some reason the subscription is undefined in the getCars() function when I try to unsubscribe from it.
What could be the reason that the subscription is undefined only when running the test? Could it have something to do with the way I've mocked the getAll() function of carDetailsService?