12

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

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

4

2 回答 2

8

Mocha has built-in Promise support as of version 1.18.0 (March 2014). You can return a promise from a test case, and Mocha will wait for it:

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

Don't forget the return keyword on the second line. If you accidentally omit it, Mocha will assume your test is synchronous, and it won't wait for the .then function, so your test will always pass even when the assertion fails.


If this gets too repetitive, you may want to use the chai-as-promised library, which gives you an eventually property to test promises more easily:

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

Again, don't forget the return keyword!

于 2015-12-06T14:50:48.830 回答
4

然后“返回”一个可用于处理错误的承诺。大多数库都支持一种方法done,该方法将确保抛出任何未处理的错误。

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

您还可以使用mocha-as-promised 之类的东西(其他测试框架也有类似的库)。如果您正在运行服务器端:

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'
于 2013-02-25T13:22:17.573 回答