【问题标题】:How to test promises with Mocha如何使用 Mocha 测试 Promise
【发布时间】:2013-02-10 02:48:48
【问题描述】:

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

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

【问题讨论】:

  • 创建一个函数,它接收it 并返回一个你调用的函数,而不是它自动完成所有这些。您的测试功能需要以 return getSomePromise() 开头
  • “当这个断言失败时,它就会被吞没”。澄清一下,value.should.equal 抛出的异常被调用“成功”回调的函数捕获。这是 Promises/A+ 的一个特性,可确保您始终可以在 Promise 链末尾的“失败”回调中处理任何错误(异常或其他)。

标签: javascript mocha.js chai es6-promise chai-as-promised


【解决方案1】:

从 1.18.0 版(2014 年 3 月)开始,Mocha 已内置 Promise 支持。你可以从一个测试用例中返回一个 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-as-promised 库,它为您提供了一个 eventually 属性来更轻松地测试 Promise:

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 关键字!

【讨论】:

  • 对不起,我不明白,我有一个简单的测试browser.url(..); title = browser.getTitle(); expect(title).to.equal('foo');我将如何使用getPromise()?
【解决方案2】:

然后“返回”一个可用于处理错误的承诺。大多数库都支持称为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'

【讨论】:

    猜你喜欢
    • 2017-02-04
    • 2017-04-08
    • 2015-02-17
    • 2014-12-21
    • 2015-07-16
    • 2017-10-07
    • 2015-12-01
    • 2016-12-30
    相关资源
    最近更新 更多