如何测试返回 Promise 的方法
How to test a method returning a Promise
我正在编写 Angular 2 RC5 应用程序,并使用 Karma 和 Jasmine 进行单元测试。
我有一个方法 returns a Promise<Foo>
(它在调用 angular 的 http.post) 我想 运行 完成后的一些断言。
这样的东西行不通
let result = myService.getFoo();
result.then(rslt => expect(1+1).toBe(3)); // the error is lost
这会创建一个 'Unhandled Promise rejection' 警告,但错误会被抑制并且测试通过。 我如何运行 断言基于我已解决的承诺?
备注:
- .catch() 方法似乎不是我想要的。我不想记录或做任何继续正常程序流程的事情,我想让测试失败。
- 我见过类似
$rootScope.$digest();
的代码。我不确定这类事情的打字稿等价物是什么。好像没有办法说:"I have a promise, I'm going to wait here until I have a synchronous result".
测试应如下所示:
it('should getFoo', function (done) {
let result = myService.getFoo();
result
.then(rslt => expect(rslt).toBe('foo'))
.then(done);
});
使用 done
回调有效,但您也应该能够这样做:
(注意return
)
it('should getFoo', function () {
let result = myService.getFoo();
return result
.then(rslt => expect(rslt).toBe('foo'))
});
我正在编写 Angular 2 RC5 应用程序,并使用 Karma 和 Jasmine 进行单元测试。
我有一个方法 returns a Promise<Foo>
(它在调用 angular 的 http.post) 我想 运行 完成后的一些断言。
这样的东西行不通
let result = myService.getFoo();
result.then(rslt => expect(1+1).toBe(3)); // the error is lost
这会创建一个 'Unhandled Promise rejection' 警告,但错误会被抑制并且测试通过。 我如何运行 断言基于我已解决的承诺?
备注:
- .catch() 方法似乎不是我想要的。我不想记录或做任何继续正常程序流程的事情,我想让测试失败。
- 我见过类似
$rootScope.$digest();
的代码。我不确定这类事情的打字稿等价物是什么。好像没有办法说:"I have a promise, I'm going to wait here until I have a synchronous result".
测试应如下所示:
it('should getFoo', function (done) {
let result = myService.getFoo();
result
.then(rslt => expect(rslt).toBe('foo'))
.then(done);
});
使用 done
回调有效,但您也应该能够这样做:
(注意return
)
it('should getFoo', function () {
let result = myService.getFoo();
return result
.then(rslt => expect(rslt).toBe('foo'))
});