0
0
Node.jsframework~10 mins

Test lifecycle hooks (before, after) in Node.js - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Test lifecycle hooks (before, after)
Start Test Suite
Run before hook
Run each test
Run after hook
End Test Suite
The test suite starts by running the 'before' hook once, then runs all tests, and finally runs the 'after' hook once.
Execution Sample
Node.js
const assert = require('assert');
before(() => { console.log('Setup'); });
after(() => { console.log('Cleanup'); });
describe('Sample', () => {
  it('test 1', () => { assert.strictEqual(1, 1); });
  it('test 2', () => { assert.strictEqual(2, 2); });
});
This code runs a setup before tests, two tests, then a cleanup after all tests.
Execution Table
StepActionOutputNotes
1Run before hookSetupRuns once before all tests
2Run test 1PassFirst test runs
3Run test 2PassSecond test runs
4Run after hookCleanupRuns once after all tests
5EndAll tests doneTest suite finished
💡 All tests executed; before and after hooks run once each.
Variable Tracker
VariableStartAfter before hookAfter test 1After test 2After after hook
setupDonefalsetruetruetruetrue
testsRun00122
cleanupDonefalsefalsefalsefalsetrue
Key Moments - 2 Insights
Why does the 'before' hook run only once before all tests?
The 'before' hook is designed to prepare the environment once before any tests run, as shown in execution_table step 1.
Does the 'after' hook run after each test or once after all tests?
The 'after' hook runs once after all tests complete, not after each test, as seen in execution_table step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 2?
ASetup
BPass
CCleanup
DFail
💡 Hint
Check the 'Output' column for step 2 in the execution_table.
At which step does the cleanup happen according to the execution table?
AStep 1
BStep 2
CStep 4
DStep 5
💡 Hint
Look for 'Cleanup' in the 'Output' column.
If we add a third test, how would 'testsRun' change after that test in variable_tracker?
AIt would become 3
BIt would stay 2
CIt would reset to 0
DIt would become 4
💡 Hint
See how 'testsRun' increments after each test in variable_tracker.
Concept Snapshot
Test lifecycle hooks run code at specific times:
- before(): runs once before all tests
- after(): runs once after all tests
- Tests run between these hooks
Use them to setup and cleanup test environment.
Full Transcript
In Node.js testing, lifecycle hooks like before and after help run code before and after tests. The before hook runs once before any tests start, setting up the environment. Then each test runs one by one. After all tests finish, the after hook runs once to clean up. This flow ensures tests run in a prepared environment and resources are cleaned after. The execution table shows the order: before hook runs first, then tests, then after hook. Variables track setup and cleanup states. This helps beginners see when and how hooks run in relation to tests.