Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

mocha
hooks
testing
javascript

What are hooks in Mocha?

Educative Answers Team

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring