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.

svg viewer

Syntax

afterEach(name, fn)

  • name: Optional string
  • fn: Function to run after each test case
var assert = require('assert');
// A test suite or block for testing sum function
describe('#sum', function () {
// Test case 1
it('sum() adds multiple numbers', function () {
assert.equals(sum(1, 2, 3), 6);
});
// Test case 2
it('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 also beforeEach(), which runs before every test case. Read more in the official docs.

Copyright ©2024 Educative, Inc. All rights reserved