Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking service calls that return observables in Angular 2?

Tags:

angular

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?

like image 462
vinnylinux Avatar asked Mar 29 '17 14:03

vinnylinux


People also ask

What is the use of observable in angular?

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.

What are the services in angular?

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.

What is new in AngularJS?

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.

What are rxjs and observables in angular?

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.


1 Answers

Somewhere in your test code I believe you need to have this code:

AuthHttp.post('/api/stuff', {id : 123 }).subscribe(data => {});
like image 61
birwin Avatar answered Sep 29 '22 09:09

birwin