Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 636
firasKoubaa Avatar asked Sep 04 '26 23:09

firasKoubaa


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);
like image 91
Guy Yogev Avatar answered Sep 07 '26 17:09

Guy Yogev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!