Performance: Test lifecycle hooks (before, after)
This concept affects test execution speed and resource usage during automated testing.
describe('My tests', () => { before(() => { // setup once before all tests initializeDatabaseConnection(); }); after(() => { // cleanup once after all tests closeDatabaseConnection(); }); it('test 1', () => { // test code }); it('test 2', () => { // test code }); });
describe('My tests', () => { beforeEach(() => { // expensive setup repeated before every test initializeDatabaseConnection(); }); afterEach(() => { // cleanup repeated after every test closeDatabaseConnection(); }); it('test 1', () => { // test code }); it('test 2', () => { // test code }); });
| Pattern | Setup Calls | Teardown Calls | Total Test Time Impact | Verdict |
|---|---|---|---|---|
| beforeEach/afterEach for all tests | N (number of tests) | N (number of tests) | High - setup/teardown repeated for each test | [X] Bad |
| before/after once per suite | 1 | 1 | Low - setup/teardown done once | [OK] Good |
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