node.js - 断言正在破坏 Mocha 测试中的异步功能

标签 node.js testing promise mocha.js

我正在构建一个 Node 模块,并尽力对其进行单元测试。我已经设置了 mocha 和 chai 来进行测试处理。我在测试异步方法(返回 promise 的方法)时遇到问题。

在下面的测试中,我正在“升级”对象上测试一个方法。

  it('Should return a list of versions for the default git repo', function (done) {
    fs.writeFileSync(appSetup.CONFIG_FILENAME, JSON.stringify(appSetup.DEFAULT_CONFIG));

    var upgrade = new Upgrade({
      quiet: true
    });

    upgrade.getVersions().then(function (versions) {
      assert(versions && versions.length > 0, 'Should have at least one version.');
      assert.equal(1, 2); // this throws the exception which causes the test case not even exist
      done();
    }, done);
  });

getVersions() 调用返回一个 promise ,因为该方法是异步的。当 promise 解决时,我想测试 versions 变量中返回的值。

assert(versions && versions.length > 0, 'Should have at least one version.'); 是实际测试。我添加了 assert.equal(1, 2); 因为我注意到当测试失败时测试用例甚至不会出现在测试列表中。

我假设 assert 调用抛出了 Mocha 应该拾取的异常。然而,它陷入了 promise then 处理函数中。

这是怎么回事?为什么当断言在该方法中失败时,它不在列表中显示测试用例(它不显示为失败;就像它不存在一样)?

最佳答案

问题的核心是您拥有的代码本质上是:

try {
  var versions = upgrade.getVersions();
} catch (err){
  return done(err);
}

assert(versions && versions.length > 0, 'Should have at least one version.');
assert.equal(1, 2); // this throws the exception which causes the test case not even exist
done();

看一下,应该清楚如果断言抛出,则两者回调都不会运行。

try {
  var versions = upgrade.getVersions();
  assert(versions && versions.length > 0, 'Should have at least one version.');
  assert.equal(1, 2); // this throws the exception which causes the test case not even exist
  done();
} catch (err){
  return done(err);
}

更像是你想要的,这将是:

upgrade.getVersions().then(function (versions) {
  assert(versions && versions.length > 0, 'Should have at least one version.');
  assert.equal(1, 2); // this throws the exception which causes the test case not even exist
}).then(done, done);

Node ,这将执行断言,然后将回调移动到将始终处理错误的辅助 .then()

也就是说,简单地返回 promise 会容易得多

return upgrade.getVersions().then(function (versions) {
  assert(versions && versions.length > 0, 'Should have at least one version.');
  assert.equal(1, 2); // this throws the exception which causes the test case not even exist
});

让 Mocha 在没有回调的情况下监控 promise 本身。

关于node.js - 断言正在破坏 Mocha 测试中的异步功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28181015/

相关文章:

node.js - 无法连接到 redis 以与多个工作人员一起使用

html - 从 Mongoose 查询数据并显示在html页面上

javascript - 如何使用 Mocha/Chai 检查文件名是否包含字符串?

javascript - NodeJs Mongoose Promise then/catch

javascript - Graphql 解析器未返回任何数据

javascript - node.js:使用等待消耗 promise

javascript - 为什么我不能在 Node 中设置时刻区域设置?

Laravel:如何为发送电子邮件的通知编写集成测试

testing - 具有使用服务的助手的 Ember 测试组件

javascript - JavaScript Promise 中异步失败引发异常