如何解决MochaJS:如何在全局Mocha实例中调用规范级挂钩?
是否有一种方法可以在每个规范之前和之后运行钩子?
例如,有3个*.spec.js
文件,控制台标准输出应如下所示。
(我知道这可以在单个规范本身的钩子之前完成。但这将意味着在所有规范文件中编写很多重复的代码。)
有rootHooks,但是它们在所有规格运行之前和之后打印。我的要求是在每个规格之前和之后打印(而不是在整个套件之前和之后打印)
Spec started at : 12:00:00 (<-- called from global spec level beforeHook)
✓ Spec 1 tests
✓ ...
✓ ...
Spec Ended at : 12:00:10 (<-- called from global spec level afterHook)
Spec started at : 12:00:11 (<-- called from global spec level beforeHook)
✓ Spec 2 tests
✓ ...
✓ ...
Spec Ended at : 12:00:15 (<-- called from global spec level afterHook)
Spec started at : 12:00:15 (<-- called from global spec level beforeHook)
✓ Spec 3 tests
✓ ...
✓ ...
Spec Ended at : 12:00:20 (<-- called from global spec level afterHook)
解决方法
我相信您可以使用root hook。
// test/timer-hooks.js
function timer() {
// Get the time and format it as a string
}
exports.mochaHooks = {
beforeEach(done) {
console.log(`Spec started at : ${timer()}`);
done();
},afterEach(done) {
console.log(`Spec ended at : ${timer()}`);
done();
}
};
然后,在运行测试时,添加--require test/timer-hooks.js
。
mocha --require test/timer-hooks.js
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。