如何用Mocha测试承诺

How to test promises with Mocha

本文关键字:承诺 测试 Mocha 何用      更新时间:2023-09-26

我正在使用Mocha测试一个返回promise的异步函数。

测试promise解析为正确值的最佳方法是什么?

Mocha自1.18.0版本(2014年3月(起已内置Promise支持。你可以从测试用例中返回一个承诺,Mocha会等待它:

it('does something asynchronous', function() { // note: no `done` argument
  return getSomePromise().then(function(value) {
    expect(value).to.equal('foo');
  });
});

不要忘记第二行的return关键字。如果你不小心忽略了它,Mocha会假设你的测试是同步的,它不会等待.then函数,所以即使断言失败,你的测试也会一直通过。


如果这太重复了,您可能需要使用chai作为承诺库,它为您提供了一个eventually属性,可以更容易地测试承诺:

it('does something asynchronous', function() {
  return expect(getSomePromise()).to.eventually.equal('foo');
});
it('fails asynchronously', function() {
  return expect(getAnotherPromise()).to.be.rejectedWith(Error, /some message/);
});

同样,不要忘记return关键字!

然后"返回"一个可用于处理错误的promise。大多数库都支持一个名为done的方法,该方法将确保抛出任何未处理的错误。

it('does something asynchronous', function (done) {
  getSomePromise()
    .then(function (value) {
      value.should.equal('foo')
    })
    .done(() => done(), done);
});

您也可以按照承诺使用类似mocha的东西(其他测试框架也有类似的库(。如果您运行的是服务器端:

npm install mocha-as-promised

然后在脚本的开头:

require("mocha-as-promised")();

如果您正在运行客户端:

<script src="mocha-as-promised.js"></script>

然后在你的测试中,你可以返回承诺:

it('does something asynchronous', function () {
  return getSomePromise()
    .then(function (value) {
      value.should.equal('foo')
    });
});

或者在咖啡脚本中(根据您的原始示例(

it 'does something asynchronous', () ->
  getSomePromise().then (value) =>
    value.should.equal 'foo'