Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock an Observable.throw in an Angular2 test?

Tags:

I want to test the error handling in my Angular2 component and therefore want to mock a service to return an Observable.throw('error'). How can that be done using Jasmine and Karma and Angular 2?

like image 366
Stefan Avatar asked Dec 05 '16 08:12

Stefan


People also ask

How do you mock a function in Angular testing?

A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.

Why would you use a spy in a test in Angular?

Spy is a feature in Jasmine that allows you to spy on something to achieve the following goals: Monitor if a function is called along with the parameters pass to it. Override function return values or properties to simulate desired situations during tests. Override the implementation of functions completely.


2 Answers

Here is my solution for the ones using Rxjs 6

let mockService = {   getData: () => {     return of({data:'any data'});   } }  spyOn(mockService , 'getData').and.callFake(() => {   return throwError(new Error('Fake error')); }); 
like image 129
Fabien Avatar answered Nov 07 '22 21:11

Fabien


You should create an observable, and just call the observer error. For example

let mockService = {   error: false,   data: 'something',   getData: () => {     return Observable.create(observer => {       if (this.error) {         observer.error(new Error(..))       } else {         observer.next(this.data);       }       observer.complete();     })   } } 

Now for your tests, you can use the mock for both success cases and error cases. For an error case, just set the error property to true. In the success case, next is called with the data.

When you subscribe to an observable, you can pass three callback, success, error, and complete

service.getData().subscribe(   (data) => {}   // sucess   (error) => {}  // error   () => {}       // complete ) 

So with the observer, when calling observer.next, observer.error, observer.complete, the corresponding callback will be called.

like image 22
Paul Samsotha Avatar answered Nov 07 '22 20:11

Paul Samsotha