javascript - 是否存在模仿 should.throws 的 shouldjs 函数?

标签 javascript promise should.js

我正在编写一个测试 promise 返回函数的测试套件。这些测试的一个共同主题是需要检查返回 promise 的函数在传递无效参数时是否正确抛出错误。我尝试过使用 should.throws,但在查看代码时我发现它不是为使用 promises 而设计的。

我已经制作了以下实用函数来获得我需要的功能:

var TestUtil = module.exports;
var should = require('should');

/**
 * Checks if a promise chain throws an error, and optionally that the error includes
 * the given errorMsg
 * @param promise {String} (optional) error message to check for
 * @param errorMsg
 */
TestUtil.throws = function(promise, errorMsg) {
  return promise
  .then(function(res) {
throw new Error(); // should never reach this point
  })
  .catch(function(e) {
if (errorMsg) {
  e.message.should.include(errorMsg);
}
should.exist(e);
  });
};

是否存在做同样事情的 shouldjs 函数?我想通过只使用 shouldjs api 来检查而不是使用这个一次性函数来保持我的测试的内聚性。

最佳答案

正如 den bardadym 所说,我正在寻找的是 .rejectedWith,它是 shouldjs 的 promise 断言函数之一。你可以这样使用它(直接从 shouldjs 的 API 文档中复制):

function failedPromise() {
  return new Promise(function(resolve, reject) {
    reject(new Error('boom'))
  })
}
failedPromise().should.be.rejectedWith(Error);
failedPromise().should.be.rejectedWith('boom');
failedPromise().should.be.rejectedWith(/boom/);
failedPromise().should.be.rejectedWith(Error, { message: 'boom' });
failedPromise().should.be.rejectedWith({ message: 'boom' });

// test example with mocha it is possible to return promise
it('is async', () => {
   return failedPromise().should.be.rejectedWith({ message: 'boom' });
});

关于javascript - 是否存在模仿 should.throws 的 shouldjs 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36375905/

相关文章:

javascript - 创建一个接受回调并返回 Promise 的 api

javascript - 为什么我的 Promise 链不能以这种嵌套方式工作?

c++ - 我可以将 should.js 与 QtScript 一起使用吗?

javascript - 将 "app access tokens"与 Facebook Javascript SDK 一起使用吗?

javascript - 带有 sqldb 服务的 Bluemix : Node. js 示例(VCAP_SERVICES 凭证)

javascript - 当尝试在变量上推送值时推送未定义而不是值

typescript - 使用 TypeScript 的 should.js 问题

javascript - Angular 方法装饰器如何工作?

javascript bluebird Promise -> 从异步列表中获取第一个文件

javascript - `for` 循环中的 Mocha 单元测试和断言