0
0
Node.jsframework~5 mins

Test lifecycle hooks (before, after) in Node.js

Choose your learning style9 modes available
Introduction

Test lifecycle hooks help you run code before or after your tests. This keeps tests clean and avoids repeating setup or cleanup steps.

You want to prepare data or environment before running tests.
You need to reset or clean resources after tests finish.
You want to open a database connection before tests and close it after.
You want to initialize variables or mock functions once before tests.
You want to log or report results after all tests run.
Syntax
Node.js
before(() => {
  // code to run once before all tests
});
after(() => {
  // code to run once after all tests
});
beforeEach(() => {
  // code to run before each test
});
afterEach(() => {
  // code to run after each test
});

before runs once before all tests in a file or suite.

after runs once after all tests finish.

beforeEach and afterEach run before and after each individual test.

Examples
This runs once before any test starts.
Node.js
before(() => {
  console.log('Setup before all tests');
});
This runs once after all tests finish.
Node.js
after(() => {
  console.log('Cleanup after all tests');
});
These run before and after every single test.
Node.js
beforeEach(() => {
  console.log('Runs before each test');
});
afterEach(() => {
  console.log('Runs after each test');
});
Sample Program

This example shows how before sets the initial count, beforeEach increments it before each test, and afterEach logs the count after each test. after runs once after all tests.

Node.js
import { describe, it, before, after, beforeEach, afterEach } from 'mocha';
import assert from 'assert';

let count = 0;

describe('Counter tests', () => {
  before(() => {
    console.log('Starting tests');
    count = 10; // setup before all tests
  });

  after(() => {
    console.log('Tests finished');
  });

  beforeEach(() => {
    count += 1; // increment before each test
  });

  afterEach(() => {
    console.log(`Count after test: ${count}`);
  });

  it('should be 11 in first test', () => {
    assert.strictEqual(count, 11);
  });

  it('should be 12 in second test', () => {
    assert.strictEqual(count, 12);
  });
});
OutputSuccess
Important Notes

Use lifecycle hooks to avoid repeating setup or cleanup code in every test.

Hooks run in the order: before -> beforeEach -> test -> afterEach -> after.

If a hook fails, it can stop tests from running, so keep hook code simple and reliable.

Summary

Lifecycle hooks help prepare and clean up around tests.

before and after run once; beforeEach and afterEach run around every test.

They keep tests organized and avoid repeated code.