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