Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

mocha
testing
javascript
aftereach

Mocha afterEach

Educative Answers Team

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.

RELATED TAGS

mocha
testing
javascript
aftereach
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring