The `beforeEach()` Hook in Mocha

Jul 19, 2023

By default, Mocha's BDD interface adds a global beforeEach() function. You can call beforeEach() with a function, and Mocha will execute that function before every test in the suite.

beforeEach(function() {
  console.log('Running beforeEach!');
});

// Prints "Running beforeEach!"
it('test1', function() {});
// Prints "Running beforeEach!"
it('test2', function() {});

With describe()

describe() lets you scope beforeEach() hooks. If you define a beforeEach() in a describe(), Mocha will not run that beforeEach() on any tests outside of that describe().

beforeEach(function() {
  console.log('Running global beforeEach!');
});

describe('my test suite', function() {
  beforeEach(function() {
    console.log('Running my test suite beforeEach!');
  });

  // Prints both "Running beforeEach!" and "Running my test suite beforeEach!"
  it('test1', function() {});
  // Prints both "Running beforeEach!" and "Running my test suite beforeEach!"
  it('test2', function() {});
});

// Only prints "Running global beforeEach!"
it('test3', function() {});

So a global beforeEach() will run on every test, even tests within a describe(). But a beforeEach() hook within a describe() will not run on any test outside of that describe().

Skipped Tests

Mocha will not run beforeEach() if there are no tests. For example, if you run a single Mocha test using .only(), Mocha will not execute the beforeEach() hook in the following test file.

describe('my test suite', function() {
  beforeEach(function() {
    console.log('Running my test suite beforeEach!');
  });

  it('test1', function() {});
  it('test2', function() {});
});

// Because of `.only()`, Node will **not** print
// "Running my test suite beforeEach!"
it.only('test3', function() {});

Working Around Linters

By default, linters like ESLint complain that beforeEach() is not defined. There are a couple of workarounds. First, you can explicitly import beforeEach() from Mocha:

const { beforeEach } = require('mocha');

Or, you can set the ESLint Mocha environment in a .eslintrc.js in your test folder as follows. For example, Mongoose uses this approach to avoid having to explicitly import Mocha hooks.

// .eslintrc.js
module.exports = {
  env: {
    mocha: true
  }
};

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Mocha Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!