Search code examples
unit-testingjasmineangularobservable

Unit testing an observable in Angular 2


What is the correct way of unit testing a service returning an Observable result in Angular 2? Let's say we have a getCars method in a CarService service class:

...
export class CarService{
    ...
    getCars():Observable<any>{
        return this.http.get("http://someurl/cars").map( res => res.json() );
    }
    ...
}

If I try to write the tests in the following way I get the warning: 'SPEC HAS NO EXPECTATIONS':

it('retrieves all the cars', inject( [CarService], ( carService ) => {
     carService.getCars().subscribe( result => {         
         expect(result.length).toBeGreaterThan(0);
     } );       
}) );

Using injectAsync does not help because it works with Promise objects as far as I could see.


Solution

  • Finally I end with a working example. Observable class has a method toPromise that converts an Observable to a Promise object. The correct way should be:

    it('retrieves all the cars', injectAsync( [CarService], ( carService ) => {
      return carService.getCars().toPromise().then( (result) => {         
         expect(result.length).toBeGreaterThan(0);
      } );       
    }) );
    

    But while to above code works with any Observable object, I still have the problem with the Observables returned from Http requests which is probably a bug. Here is a plunker demonstrating the case above: http://plnkr.co/edit/ak2qZH685QzTN6RoK71H?p=preview

    Update:
    As of version beta.14 it seems to work properly with the provided solution.