使用带延迟标志的 mocha 出现无提示错误
我们在开源项目 https://opentermsarchive.org 上使用 mocha,并最终在 CI 中部署我们的代码,尽管测试中的错误。
问题是这些错误会默默地失败,退出代码为 0,这非常糟糕。
这意味着
- 测试已启动
- 测试失败且没有错误
- CI 认为测试已通过,即使它们没有完全运行
我们正在通过以下配置以编程方式使用 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);
});
})();
We are using mocha on our Open Source project https://opentermsarchive.org and ended up in the CI deploying our code despite errors in the tests.
Problem is that those errors failed silently with an exit code of 0, which is really bad.
This means
- tests are launched
- tests fail with no error
- CI considers tests have passed even though they did not run completely
We are using mocha programmatically with the following config
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);
});
})();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这
是因为当您使用
delay
属性时,mocha 会静默unhandledRejection
您可以在此处看到 https://github.com/mochajs/mocha/blob/master/lib/runner.js#L198
所以绕过这个的方法是
在 mocha 实例化之前添加
Well
this is due to the fact that mocha is silenting
unhandledRejection
when you are using thedelay
propertyYou can see that here https://github.com/mochajs/mocha/blob/master/lib/runner.js#L198
So a way to bypass this is to add
before the instantiation of mocha