What are hooks in Mocha?

Mocha is a feature-rich JavaScript test framework for Node.js.
Mocha provides several built-in hooks that can be used to set up preconditions and clean up after your tests. The four most commonly used hooks are: before(), after(), beforeEach(), and afterEach().

svg viewer

Syntax

before(name, fn)

  • name: Optional string for description
  • fn: Function to run once before the first test case

after(name, fn)

  • name: Optional string for description
  • fn: Function to run once after the last test case

beforeEach(name, fn)

  • name: Optional string for description
  • fn: Function to run before each test case

afterEach(name, fn)

  • name: Optional string for description
  • fn: Function to run after each test case

All hooks may also be sync or async.

Mocha also provides root hooks that run before or after every test in every file. Read more about them here.

Code

The hooks run in the order:

  1. all before() hooks run (once)
  2. any beforeEach() hooks or tests
  3. any afterEach() hooks
  4. after() hooks (once)
describe('hooks', function () {
before('optional description', function () {
// runs once before the first test in this block
});
after('optional description', function () {
// runs once after the last test in this block
});
beforeEach('optional description', function () {
// runs before each test in this block
});
afterEach('optional description', function () {
// runs after each test in this block
});
// example test cases
it('test case 1', function () {
// ...
});
// Test case 2
it('test case 2', function () {
// ...
});
});
Copyright ©2024 Educative, Inc. All rights reserved