Unit testing an observable in Angular 2

后端 未结 6 1939
灰色年华
灰色年华 2020-12-24 10:17

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:

<         


        
6条回答
  •  春和景丽
    2020-12-24 10:46

    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.

提交回复
热议问题