Test lifecycle hooks help you run code before or after your tests. This keeps tests clean and avoids repeating setup or cleanup steps.
Test lifecycle hooks (before, after) in 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.
before(() => {
console.log('Setup before all tests');
});after(() => {
console.log('Cleanup after all tests');
});beforeEach(() => {
console.log('Runs before each test');
});
afterEach(() => {
console.log('Runs after each test');
});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.
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); }); });
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.
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.