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().
Syntax
before(name, fn)
name: Optional string for descriptionfn: Function to run once before the first test case
after(name, fn)
name: Optional string for descriptionfn: Function to run once after the last test case
beforeEach(name, fn)
name: Optional string for descriptionfn: Function to run before each test case
afterEach(name, fn)
name: Optional string for descriptionfn: 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:
- all
before()hooks run (once) - any
beforeEach()hooks or tests - any
afterEach()hooks 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 casesit('test case 1', function () {// ...});// Test case 2it('test case 2', function () {// ...});});
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved