Mocha Hooks

HOOKS

With its default “BDD”-style interface, Mocha provides the hooks before(), after(), beforeEach(), and afterEach(). These should be used to set up preconditions and clean up after your tests.

describe(‘hooks’, function() {

before(function() {
// runs before all tests in this block
});

after(function() {
// runs after all tests in this block
});

beforeEach(function() {
// runs before each test in this block
});

afterEach(function() {
// runs after each test in this block
});

// test cases
});
Tests can appear before, after, or interspersed with your hooks. Hooks will run in the order they are defined, as appropriate; all before() hooks run (once), then any beforeEach() hooks, tests, any afterEach() hooks, and finally after() hooks (once).

DESCRIBING HOOKS

Any hook can be invoked with an optional description, making it easier to pinpoint errors in your tests. If a hook is given a named function, that name will be used if no description is supplied.

beforeEach(function() {
// beforeEach hook
});

beforeEach(function namedFun() {
// beforeEach:namedFun
});

beforeEach(‘some description’, function() {
// beforeEach:some description
});
ASYNCHRONOUS HOOKS

All hooks (before(), after(), beforeEach(), afterEach()) may be sync or async as well, behaving much like a regular test-case. For example, you may wish to populate database with dummy content before each test:

describe(‘Connection’, function() {
var db = new Connection,
tobi = new User(‘tobi’),
loki = new User(‘loki’),
jane = new User(‘jane’);

beforeEach(function(done) {
db.clear(function(err) {
if (err) return done(err);
db.save([tobi, loki, jane], done);
});
});

describe(‘#find()’, function() {
it(‘respond with matching records’, function(done) {
db.find({type: ‘User’}, function(err, res) {
if (err) return done(err);
res.should.have.length(3);
done();
});
});
});
});
ROOT-LEVEL HOOKS

You may also pick any file and add “root”-level hooks. For example, add beforeEach() outside of all describe() blocks. This will cause the callback to beforeEach() to run before any test case, regardless of the file it lives in (this is because Mocha has an implied describe() block, called the “root suite”).

beforeEach(function() {
console.log(‘before every test in every file’);
});
DELAYED ROOT SUITE

If you need to perform asynchronous operations before any of your suites are run, you may delay the root suite. Run mocha with the –delay flag. This will attach a special callback function, run(), to the global context:

setTimeout(function() {
// do some setup

describe(‘my suite’, function() {
// …
});

run();
}, 5000);

Questions