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.
before hook in Node.js testing frameworks like Mocha?before hookbefore hook runs once before all tests in a test suite to prepare the environment.beforeEach runs before each test, and after runs after all tests, so they do not match the question.before = setup once before all tests [OK]beforeEach hook in Mocha?beforeEach(() => { ... }) to define hooks.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?before runs once: count = 0 + 1 = 1.test 1: count = 1 + 100 = 101.test 2: count = 101 + 1000 = 1101.after: count = 1101 + 10 = 1111.beforeEach or afterEach hooks affect count, so final is 1111.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?before runs once before all tests, so 'Setup' prints first.after runs printing 'Cleanup'.before hook.after hook.before to open and after to close -> Option APass the test and this pattern moves unknown