单元测试Angular 2中的可观察量 [英] Unit testing an observable in Angular 2

查看:95
本文介绍了单元测试Angular 2中的可观察量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 2中单元测试返回Observable结果的服务的正确方法是什么?假设我们在CarService服务类中有一个getCars方法:

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() );
    }
    ...
}

如果我尝试按以下方式写测试我收到警告:'SPEC没有预期':

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);
     } );       
}) );

使用injectAsync无济于事,因为它适用于 Promise 对象,据我所知。

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

推荐答案

最后,我以一个有效的例子结束。 Observable 类有一个方法toPromise,它将Observable转换为Promise对象。正确的方法应该是:

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);
  } );       
}) );

但是上面的代码适用于任何Observable对象,我仍然遇到<$ c的问题$ c>从Http请求返回的Observable 可能是一个bug。这是一个展示上述案例的傻瓜: http://plnkr.co/edit/ak2qZH685QzTN6RoK71H?p=预览


更新:

从版本beta.14开始,它似乎与提供的解决方案一起正常运行。

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.

这篇关于单元测试Angular 2中的可观察量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆