用 Jasmine 惯用地测试 when.js promises

Idiomatically testing when.js promises with Jasmine

我正在为 returns when.js 承诺的代码编写一些 Jasmine 单元测试。我一直发现自己在编写这样的代码:

doMyThing().then(function(x) {
  expect(x).toEqual(42);
  done();
}).otherwise(function() {
  expect(true).toBe(false);
  done();
});

捕获异常的唯一方法是使用 otherwise() 函数(它是 when.js 的旧版本),然后似乎没有 Jasmine (2.0) 函数来说 "failure detected" - 因此是笨拙的“expect(true).toBe(false)”。

有没有更惯用的方法来做到这一点?

您应该考虑像 Mocha 这样具有承诺支持的测试库,或者使用像 jasmine-as-promised 这样的帮助程序来为您提供这种语法。这会让你做一些事情:

// notice the return, and _not_ passing `done` as an argument to `it`:
return doMyThing().then(function(x) {
  expect(x).toEqual(42);
});

基本上,return 值被检查为一个承诺,如果它是测试框架检查承诺是否被拒绝并将其视为失败。

在更仔细地查看文档并意识到我们使用的是 Jasmine 2.3 之后,我发现我们可以使用 fail() 函数,它大大简化了事情。问题中的示例变为:

doMyThing().then(function(x) {
  expect(x).toEqual(42);
}).otherwise(fail).then(done);

如果 doMyThing() 抛出异常,该错误将传递给 fail() 并打印堆栈跟踪。

这个.otherwise(fail).then(done);原来是一个非常方便的成语。