断言正在破坏摩卡测试中的异步功能

Assert Is Breaking Async Function in Mocha Test

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

在下面的测试中,我正在 "Upgrade" 对象上测试一个方法。

  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() 调用 return 是一个承诺,因为该方法是异步的。当承诺解决时,我想测试 returned 在 versions 变量中的值。

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

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

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

在您调用回调之前,测试不会出现在列表中,如果断言失败,则不会发生这种情况。您需要在最终承诺上调用 .catch(done) 以确保始终调用 done

如果您给它一个超时值,测试 将会 出现,您可能应该这样做。

综上所述,mocha 理解承诺。你根本不需要处理回调:

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

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

    return upgrade.getVersions().then(function (versions) {
      assert(versions && versions.length > 0, 'Should have at least one version.');
      assert.equal(1, 2);
    });
  });

问题的核心是你的代码本质上是:

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

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

也就是说,将承诺简单地 return 为

会容易得多
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 本身。