MochaJS: How to call spec level hooks in the global mocha instance?

375 views Asked by At

Is there a way to run a hook before and after each spec? Eg, there are 3 *.spec.js files, the console stdout should print as below..

(I am aware that this can be done in before hooks of the individual spec itself. But that would mean writing a lot of duplicate code in all spec files.)

There are rootHooks but they print at the before and after all the specs have run. My requirement is to print before and after each spec(not before and after the entire suite)

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

There are 1 answers

0
Chris V. On BEST ANSWER

I believe you could use a 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();
  }
};

Then, when running your tests, add the --require test/timer-hooks.js.

mocha --require test/timer-hooks.js