Jasmine : How to SpyOn a method callback : method.then()

Viewed 5554

within my Angular 4.0.0 app , i have this method , called in my component.

This method is called within a service :

    this.myService.myMethod(param).then(any => {
        console.log("success case")
    })
      .catch(error => {
            console.log("error");
        }
      });
  };

Since i'm working on unit testing , i'm isolating my component via mocking the service : i'm mocking then this method , like the following :

myMethodSpy= spyOn(service, 'myMethod').and.callFake((reg) => {
    return Observable.of('always error message');
});

But when executing , its seems that my spyMethod isn't called:

TypeError: this.service.myMethod(...).then is not a function

Any ideas , about the problem's origin ?

1 Answers
const pMock = {then: () => 'something'}
myMethodSpy= spyOn(service, 'myMethod').and.returnValue(pMock);

Or you can return an actual promise.

const pMock = new Promise((resolve, reject) => {
  resolve(someValue); 
  // or reject("failure reason"); 
});
myMethodSpy= spyOn(service, 'myMethod').and.returnValue(pMock);
Related