3

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 ?

firasKoubaa
  • 6,439
  • 25
  • 79
  • 148
  • 1
    Observables don't have a then() method. Promises do. Check the documentation/code/return type of your service method, and verify that it returns a Promise. Return a fake promise in your test. – JB Nizet Nov 07 '17 at 17:03

1 Answers1

2
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);
Guy Yogev
  • 861
  • 5
  • 14
  • Your promise could simply be created using `Promise.resolve(someValue)`. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve – JB Nizet Nov 07 '17 at 19:15
  • @Guy Yogev my method supports alos a catch callback (myMethod().then().catch() ) any idea of how spy on the catch block ?? ) – firasKoubaa Nov 08 '17 at 08:00