在 Angular 2 中对 observable 进行单元测试 [英] Unit testing an observable in 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 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: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 Observable
s 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 中对 observable 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!