Trusted answers to developer questions

What are hooks in Mocha?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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 () {
// ...
});
});

RELATED TAGS

mocha
hooks
testing
javascript
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?