Reputation: 2609
I am trying to write a test case for the following function:
foo = () => {
this.someService.getDetails({key:'value'}).subscribe(details => {
//do stuff
this.someService.getMoreDetails().subscribe(moreDetails => {
//do stuff
});
});
}
The service looks like this:
getDetails = (args) :Observable<any> {
return this.http.post<any>(//calls)
}
// similar for getMoreDetails
The test file that I have written looks like this:
const someServiceStub = jasmine.createSpyObj('someService', ['getDetails', 'getMoreDetails']);
...
...
it('should called getMoreDetails', () => {
component.foo();
fixture.detectChanges();
someServiceStub.getDetails.and.returnValue(Observable.of
({ Details: 'Tired of giving you details'})
);
expect(someServiceStub.getMoreDetails).toHaveBeenCalled();
});
However, my test case fails giving the error 'Cannot read property subscribe of undefined' (for the first line inside foo function).
I have tried using mockservice classes too but the same error comes up. What is the possible reason for this and how can I solve it?
Upvotes: 2
Views: 5949
Reputation: 692121
You start by calling the foo()
function, which calls the getDetails()
method of the service. This method is a spy, and you have never told the spy what to return, so it returns undefined.
Then, you tell the spy what to return. That's too late: the service call has already been made. Tell the spy what to return before calling foo()
.
Upvotes: 2