如何测试返回 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' 警告,但错误会被抑制并且测试通过。 我如何运行 断言基于我已解决的承诺?

备注:

测试应如下所示:

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