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.
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); }); });
| Step | Action | Output | Notes |
|---|---|---|---|
| 1 | Run before hook | Setup | Runs once before all tests |
| 2 | Run test 1 | Pass | First test runs |
| 3 | Run test 2 | Pass | Second test runs |
| 4 | Run after hook | Cleanup | Runs once after all tests |
| 5 | End | All tests done | Test suite finished |
| Variable | Start | After before hook | After test 1 | After test 2 | After after hook |
|---|---|---|---|---|---|
| setupDone | false | true | true | true | true |
| testsRun | 0 | 0 | 1 | 2 | 2 |
| cleanupDone | false | false | false | false | true |
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.