I have been trying to mock some service calls that return observables in my Angular app, but i simply can't create a valid observable that will trigger calls like catch()
or map()
in my code. For example:
My service:
create(): Observable<any> {
return this.http
.post('/api/stuff', { id: 123 })
.catch(this.handleError)
.map(this.extractData);
}
My spec:
let authHttpMock = mock(AuthHttp);
when(authHttpMock.post('/api/stuff', { id: 123 })).thenReturn(Observable.create(observer => {
observer.error(new Error('500!'));
}));
const myService = new MyService(instance(authHttpMock));
myService.create({ id: 123 }).subscribe(
result => {
expect(result).toBeTruthy();
}
);
The coverage analysis tells me that the handleError
method has never been executed. On the case of a successful observable, it also doesn't go through the extractData
method.
Where is that observable going to? How can i return a proper observable in order to test such calls?
In angular, Observables are one of the most used techniques. It is used extensively in integration with Data Services to read an API. Other than that, to access an observable, the component first needs to subscribe to the Observable.
The Services are used to create variable data that can be shared and used outside the component in which it is injected and called services. In angular services can be called from any component and data can be distributed to any component in the application. First, we need to set up an angular application and follow the steps below.
Angular brings many new concepts that can can improve our JavaScript applications. The first new concept to Angular is the use of Observables. Observables are a proposed feature coming to the JavaScript specification. I wont go in depth into Observables but will just cover some of the high level concepts.
This pattern can also be used in Angular 1. RxJS and Observables are not just an Angular feature. This may seem like a lot of work for a simple todo app but scale this up to a very large app and Observables can really help manage our data and application state. This pattern follows the idea of unidirectional data flow.
Somewhere in your test code I believe you need to have this code:
AuthHttp.post('/api/stuff', {id : 123 }).subscribe(data => {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With