Jul 19, 2023
By default, Mocha’s BDD interface provides a world beforeEach()
perform.
You possibly can name beforeEach()
with a perform, and Mocha will execute that perform earlier than each take a look at within the suite.
beforeEach(perform() {
console.log('Operating beforeEach!');
});
it('test1', perform() {});
it('test2', perform() {});
With describe()
describe()
helps you to scope beforeEach()
hooks.
In case you outline a beforeEach()
in a describe()
, Mocha won’t run that beforeEach()
on any checks outdoors of that describe()
.
beforeEach(perform() {
console.log('Operating world beforeEach!');
});
describe('my take a look at suite', perform() {
beforeEach(perform() {
console.log('Operating my take a look at suite beforeEach!');
});
it('test1', perform() {});
it('test2', perform() {});
});
it('test3', perform() {});
So a world beforeEach()
will run on each take a look at, even checks inside a describe()
.
However a beforeEach()
hook inside a describe()
won’t run on any take a look at outdoors of that describe()
.
Working Round Linters
By default, linters like ESLint complain that beforeEach()
will not be outlined.
There are a few workarounds.
First, you’ll be able to explicitly import beforeEach()
from Mocha:
const { beforeEach } = require('mocha');
Or, you’ll be able to set the ESLint Mocha atmosphere in a .eslintrc.js
in your take a look at
folder as follows.
For instance, Mongoose makes use of this strategy to keep away from having to explicitly import Mocha hooks.
module.exports = {
env: {
mocha: true
}
};