Mocha afterEach
Mocha is a JavaScript test framework for Node.js with features like browser support, asynchronous testing, test coverage report, and use of any assertion library.
afterEach() is a hook or global method provided by Mocha that will execute after each test case in a block. It is usually used to clean-up after your test cases.
Syntax
afterEach(name, fn)
name: Optional stringfn: Function to run after each test case
var assert = require('assert');// A test suite or block for testing sum functiondescribe('#sum', function () {// Test case 1it('sum() adds multiple numbers', function () {assert.equals(sum(1, 2, 3), 6);});// Test case 2it('sum() handles single number', function () {assert.equals(sum(3), 3);});afterEach(function () {// Runs after each test in this block// Will run once after test case 1 and once// after test case 2//...});});
In addition to
afterEach(), there is alsobeforeEach(), which runs before every test case. Read more in the official docs.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved