在 Angular 2 中对 observable 进行单元测试

编程入门 行业动态 更新时间:2024-10-27 20:23:57
本文介绍了在 Angular 2 中对 observable 进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 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("someurl/cars").map( res => res.json() ); } ... }

如果我尝试按以下方式编写测试,我会收到警告:SPEC HAS NO EXPECTATIONS":

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 对象,但我仍然遇到从 Http 请求返回的 Observable 的问题,这可能是一个错误.这是一个演示上述案例的 plunker: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: plnkr.co/edit/ak2qZH685QzTN6RoK71H?p=preview

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

更多推荐

在 Angular 2 中对 observable 进行单元测试

本文发布于:2023-11-14 16:19:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587934.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中对   单元测试   Angular   observable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!