简体   繁体   中英

How to mock a service call in a function in angular unit testing?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM