0

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

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

捕获异常的唯一方法是使用函数(它是when.jsotherwise()的旧版本),然后似乎没有 Jasmine(2.0)函数来表示“检测到故障” - 因此是 kludgy “ ”。expect(true).toBe(false)

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

4

2 回答 2

2

您应该考虑使用像 Mocha 这样的带有 Promise 支持的测试库,或者使用像 jasmine-as-promised 这样的帮助程序,它可以为您提供这种语法。这将使您可以按照以下方式进行操作:

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

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

于 2015-09-07T07:16:34.837 回答
0

在仔细查看文档并意识到我们正在使用 Jasmine 2.3 之后,我发现我们可以使用该fail()功能,这大大简化了事情。问题中的示例变为:

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

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

.otherwise(fail).then(done);事实证明,这是一个非常方便的成语。

于 2015-09-17T13:54:20.077 回答