Jest provides multiple lifecycle hooks to manage test setup and teardown:
beforeAll:
- Runs once before all tests in the current test suite
- Suitable for one-time setup, like database connections
- Example:
beforeAll(() => { connectDatabase(); });
afterAll:
- Runs once after all tests in the current test suite
- Suitable for cleanup, like closing database connections
- Example:
afterAll(() => { disconnectDatabase(); });
beforeEach:
- Runs before each test in the current test suite
- Suitable for per-test setup, like resetting state
- Example:
beforeEach(() => { resetState(); });
afterEach:
- Runs after each test in the current test suite
- Suitable for per-test cleanup, like clearing mocks
- Example:
afterEach(() => { jest.clearAllMocks(); });
Scope:
- Hooks are effective within the
describeblock where they're defined - Nested
describeblocks inherit parent hooks - Hooks can be defined at multiple levels
Example:
javascriptdescribe('User API', () => { beforeAll(() => setupServer()); afterAll(() => teardownServer()); beforeEach(() => { jest.clearAllMocks(); }); test('should create user', () => { /* ... */ }); test('should get user', () => { /* ... */ }); });
Best Practices:
- Use
beforeEachandafterEachfor test isolation - Use
beforeAllandafterAllfor performance optimization - Clean up mocks and timers in
afterEach - Keep hooks simple, avoid complex logic