Mocha.js: Root Hook Plugins Cheat Sheet

Defining

A Root Hook Plugin file is a script which exports (via module.exports) a mochaHooks property. It is loaded via --require <file>.

With CommonJS

exports.mochaHooks = {
  beforeEach(done) {
    // do something before every test
    done();
  },
};

With ES Modules

export const mochaHooks = {
  beforeEach(done) {
    // do something before every test
    done();
  },
};

Available Root Hooks

beforeAll:

In serial mode (Mocha’s default), before all tests begin, once only

In parallel mode, run before all tests begin, for each file

beforeEach:

In both modes, run before each test

afterAll:

In serial mode, run after all tests end, once only

In parallel mode, run after all tests end, for each file

afterEach:

In both modes, run after every test

Multiple Root Hooks In A Single Plugin

export const mochaHooks = {
  beforeEach: [
    function (done) {
      // do something before every test,
      // then run the next hook in this array
    },
    async function () {
      // async or Promise-returning functions allowed
    },
  ],
};

Multiple Root Hook Plugins

Multiple root hook plugins can be registered by using --require multiple times.

Migrating Tests To Use Root Hook Plugins

  1. Find your root hooks (hooks defined outside of a suite–usually describe() callback).
  2. Create a new file, e.g., test/hooks.js.
  3. Move your root hooks into test/hooks.js.
  4. In test/hooks.js, make your hooks a member of an exported mochaHooks property.
  5. Use --require test/hooks.js (even better: use a config file with {"require": "test/hooks.js"}) when running your tests.

Leave a Reply

Your email address will not be published. Required fields are marked *