使用带有延迟标志的 mocha 的无提示错误

Silent errors using mocha with delay flag

我们在我们的开源项目 https://opentermsarchive.org 上使用 mocha,尽管测试中存在错误,但最终 CI 部署了我们的代码。

问题是这些错误以退出代码 0 静默失败,这真的很糟糕。

这意味着

我们通过以下配置以编程方式使用 mocha

const mocha = new Mocha({
  delay: true, // as the validation script performs an asynchronous load before running the tests, the execution of the tests are delayed until run() is called
  failZero: true, // consider that being called with no service to validate is a failure
});
const VALIDATE_PATH = path.resolve(__dirname, '../scripts/validation/validate.js');

(async () => {
  mocha.addFile(VALIDATE_PATH); // As `delay` has been called, this statement will not load the file directly, `loadFilesAsync` is required.
  await mocha.loadFilesAsync() // Load files previously added to the Mocha cache with `addFile`.
    .catch(error => {
      console.error(error);
      process.exit(2);
    });

  let hasFailedTests = false;

  mocha.run()
    .on('fail', () => { hasFailedTests = true; })
    .on('end', () => {
      if (hasFailedTests) {
        process.exit(1);
      }

      process.exit(0);
    });
})();

这是因为当您使用 delay 属性

时,mocha 正在静音 unhandledRejection

你可以在这里看到 https://github.com/mochajs/mocha/blob/master/lib/runner.js#L198

所以绕过这个的方法是添加

process.on('unhandledRejection', reason => {
  // Mocha catch unhandled rejection from the user code and re-emit them to the process (see https://github.com/mochajs/mocha/blob/master/lib/runner.js#L198)
  // Re-throw them so that the validation command fails in these cases (for example, if there is a syntax error when parsing JSON declaration files)
  console.error(reason); // keep the console error to have the whole stack trace
  throw reason;
});

mocha实例化之前