2 min read
Next in trending

Hooks in Mocha

When do before(), beforeEach(), after(), and afterEach() run?

Hooks in Mocha

When do before(), beforeEach(), after(), and afterEach() run?


Mocha is a flexible Javascript testing library.

One of its main features is the ability to have certain pieces of code run either before or after certain tests. This happens with what are called “hooks.”

The four hooks in Mocha are:

  1. The beforeEach() hook contains code that runs before every test in a describe block.
  2. The afterEach() hook contains code that runs after every test in a describe block.
  3. The before() hook contains code that runs before any tests in each describe() block run. It runs before the first run of a beforeEach() hook.
  4. The after() hook contains code that runs after all tests in each describe() block have run. The after() hook will run after the last afterEach() hook.

You can use these hooks to set up variables in scope for your tests to run properly.

If you don’t yet have Mocha installed, you can install it through npm. Run at the command line:

npm install -g mocha

to install Mocha. To run Mocha on a test file, navigate to that file’s directory, then run:

mocha testfile.js

Below we have a bit of example code. In what order will statements be logged to the console?

describe(‘test the order of Mocha hooks’, function(){
 before( function(){ console.log(‘before’); });
after( function(){ console.log(‘after’); });
 beforeEach( function(){ console.log(‘beforeEach’); });
afterEach( function(){ console.log(‘afterEach’); });
 it(‘test 1', function(){ console.log(‘1'); });
it(‘test 2', function(){ console.log(‘2'); });

});
  1. We know that the before() hook runs first. So we expect ‘before’ to be the first thing logged.
  2. After that, we notice a beforeEach() hook. This will run before ‘test 1' runs. So we expect ‘beforeEach’ to run next.
  3. Now that the beforeEach() hook has run, ‘test 1' runs. ‘1' is logged to the console.
  4. The afterEach() hook now kicks in, now that a test has completed. ‘afterEach’ is logged.
  5. beforeEach() is triggered again in advance of ‘test 2.’
  6. ‘test 2' runs.
  7. afterEach() is triggered again.
  8. Finally, now that all tests have run, the after() hook runs.

See below to confirm our result.

Joeys-MacBook-Air:SocketTest joey$ mocha test.js
before
beforeEach
1
․afterEach
beforeEach
2
.afterEach
after

2 passing (7ms)

I hope this helps you write better Mocha tests!