describe('Suite', () => { before(() => console.log('before all')); after(() => console.log('after all')); beforeEach(() => console.log('before each')); afterEach(() => console.log('after each')); it('test 1', () => console.log('test 1')); it('test 2', () => console.log('test 2')); });
The before hook runs once before all tests. beforeEach runs before each test. afterEach runs after each test. after runs once after all tests.
So the order is: before all, before each, test 1, after each, before each, test 2, after each, after all.
counter after all tests run?let counter = 0; describe('Counter Suite', () => { before(() => { counter += 1; }); beforeEach(() => { counter += 2; }); afterEach(() => { counter += 3; }); after(() => { counter += 4; }); it('test 1', () => {}); it('test 2', () => {}); });
The before hook runs once: +1
beforeEach runs twice (once per test): 2 * 2 = +4
afterEach runs twice: 2 * 3 = +6
after runs once: +4
Total: 1 + 4 + 6 + 4 = 15
Option D is missing parentheses after beforeEach and uses braces incorrectly. It should be beforeEach(() => { ... }).
All other options use correct syntax.
after hook never execute?describe('My Suite', () => { before(() => { throw new Error('fail'); }); after(() => console.log('after hook')); it('test 1', () => {}); });
When a before hook fails (throws an error), Mocha aborts the entire suite: no tests execute, and after hooks do not run.
after hooks only run after the suite completes (successfully or not), but a failed before prevents suite execution.
beforeEach() runs before every test, making it ideal to reset state like database connections before each test.
before() runs once before all tests, so it won't reset between tests.
after() and afterEach() run after tests, not before.