乐闻世界logo
搜索文章和话题

What are the lifecycle hooks in Jest? How to use beforeAll, afterAll, beforeEach, and afterEach?

2月21日 15:57

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 describe block where they're defined
  • Nested describe blocks inherit parent hooks
  • Hooks can be defined at multiple levels

Example:

javascript
describe('User API', () => { beforeAll(() => setupServer()); afterAll(() => teardownServer()); beforeEach(() => { jest.clearAllMocks(); }); test('should create user', () => { /* ... */ }); test('should get user', () => { /* ... */ }); });

Best Practices:

  • Use beforeEach and afterEach for test isolation
  • Use beforeAll and afterAll for performance optimization
  • Clean up mocks and timers in afterEach
  • Keep hooks simple, avoid complex logic
标签:Jest