2021年3月30日星期二

Angular 8 karma test both success and error of Observable from service

I'm testing MyComponent that, in ngOnInit, calls a service method that returns an observable:

    this.myService.getMyData().subscribe(          (data) => {              //do something          },          (error) => {              //do something - error          }      );  

I've installed a spy on getMyData, this way:

mySpy = spyOn(myService, 'getMyData').and.returnValue(of(mockObject));  

and this covers the "success branch" of subscribe. But I need also to cover the "error branch". I've tried doing this:

spyOn(myService, 'getMyData').and.returnValue(throwError(new Error('Error')));  

but of course Jasmine tells me that getMyData has already been spied upon. How can I cover both branches?

https://stackoverflow.com/questions/66873513/angular-8-karma-test-both-success-and-error-of-observable-from-service March 30, 2021 at 11:02PM

没有评论:

发表评论