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.
Practice
before hook in Node.js testing frameworks like Mocha?Solution
Step 1: Understand the role of
Thebeforehookbeforehook runs once before all tests in a test suite to prepare the environment.Step 2: Differentiate from other hooks
beforeEachruns before each test, andafterruns after all tests, so they do not match the question.Final Answer:
To run setup code once before all tests in a suite -> Option AQuick Check:
before= setup once before all tests [OK]
- Confusing before with beforeEach
- Thinking before runs after tests
- Mixing before with afterEach
beforeEach hook in Mocha?Solution
Step 1: Recall Mocha hook syntax
Mocha uses functions likebeforeEach(() => { ... })to define hooks.Step 2: Check each option
beforeEach(() => { /* setup code */ }); uses correct arrow function syntax. before_each(() => { /* setup code */ }); uses invalid function name. beforeEach {} is incomplete syntax. beforeEach: function() { /* setup code */ } uses incorrect object notation.Final Answer:
beforeEach(() => { /* setup code */ }); -> Option BQuick Check:
Correct hook syntax uses function call with callback [OK]
- Using underscores instead of camelCase
- Omitting parentheses
- Using object notation instead of function call
let count = 0;
before(() => { count += 1; });
after(() => { count += 10; });
it('test 1', () => { count += 100; });
it('test 2', () => { count += 1000; });What is the final value of count after all tests run?Solution
Step 1: Calculate increments in order
beforeruns once: count = 0 + 1 = 1.
Thentest 1: count = 1 + 100 = 101.
Thentest 2: count = 101 + 1000 = 1101.
Finallyafter: count = 1101 + 10 = 1111.Step 2: Confirm no other increments
NobeforeEachorafterEachhooks affect count, so final is 1111.Final Answer:
1111 -> Option DQuick Check:
Sum increments: 1 + 100 + 1000 + 10 = 1111 [OK]
- Adding after hook before tests
- Forgetting before hook runs once
- Confusing beforeEach with before
before(() => { console.log('Setup'); });
after(() => { console.log('Cleanup'); });
it('test 1', () => { console.log('Test 1'); });
it('test 2', () => { console.log('Test 2'); });What is the correct order of console output?Solution
Step 1: Understand hook execution order
beforeruns once before all tests, so 'Setup' prints first.Step 2: Tests run in order, then after hook
Tests print 'Test 1' then 'Test 2'. After all tests,afterruns printing 'Cleanup'.Final Answer:
Setup, Test 1, Test 2, Cleanup -> Option CQuick Check:
before -> tests -> after = Setup, Test 1, Test 2, Cleanup [OK]
- Assuming after runs after each test
- Mixing test order
- Thinking before runs before each test
Solution
Step 1: Identify when to open connection
Opening once before all tests means usingbeforehook.Step 2: Identify when to close connection
Closing once after all tests means usingafterhook.Final Answer:
beforeto open andafterto close -> Option AQuick Check:
Open once before all, close once after all [OK]
- Using beforeEach/afterEach causing repeated open/close
- Reversing before and after roles
- Mixing hooks for different purposes
Ready to prove it?
Pass the test and this pattern moves unknown
