2

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?

0

1 Answer 1

2

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().

Sign up to request clarification or add additional context in comments.

1 Comment

O my geekiness, it helped. Can you also suggest how to proceed if I had to test in some other test case, whether the getMoreDetails() is called, where i dont want to begin testing from the foo() call but directly from the response of getDetails(). (In short testing the nested api calls without repeating the testing for previous line of code in the function)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.