Learn the concept
Test Lifecycle Hooks
These are Jest lifecycle hooks for test setup and cleanup. beforeEach/afterEach run before/after each test. beforeAll/afterAll run once before/after all tests in a describe block. Use them to set up test data, mock functions, or clean up resources.
Lifecycle Hooks:
beforeAll(): Once before all tests in blockafterAll(): Once after all tests completebeforeEach(): Before every testafterEach(): After every testCommon Use Cases:
beforeEach:
afterEach:
beforeAll:
afterAll:
describe('User service', () => {
let userService;
let mockDatabase;
// Run once before all tests
beforeAll(() => {
console.log('Setting up test suite');
mockDatabase = createMockDatabase();
});
// Run before each test
beforeEach(() => {
userService = new UserService(mockDatabase);
// Reset any mock state
jest.clearAllMocks();
});
// Run after each test
afterEach(() => {
// Clean up any side effects
userService = null;
});
// Run once after all tests
afterAll(() => {
console.log('Cleaning up test suite');
mockDatabase.close();
});
test('creates user', () => {
const user = userService.create({ name: 'Alice' });
expect(user).toHaveProperty('id');
});
test('finds user by id', () => {
const user = userService.findById(1);
expect(user).toBeDefined();
});
});Using `beforeEach` to re-initialize the component, reset mock states, or clear any global side effects before each test runs, preventing tests from impacting each other and ensuring consistent results.
Utilizing `beforeAll` to perform expensive setup operations only once at the beginning of the test file, and `afterAll` to tear down these resources, significantly speeding up the overall test execution time.
Employing `afterEach` to unmount React components, clear the JSDOM environment, or reset network mocks, ensuring that the test environment is pristine for the next test.
Create a simple application that fetches data from a mock API. Use `beforeAll` to set up Jest's mock API and `afterAll` to clean it up, demonstrating efficient test setup and teardown.
Develop a small React component and write several tests for it. Use `beforeEach` to render the component anew before each test, ensuring each test operates on an isolated component instance.
Stripe's engineering team uses Jest's setup/teardown hooks to manage complex test environments, such as mocking network requests for API clients or setting up isolated database states for integration tests, ensuring their payment infrastructure remains robust.
Airbnb leverages these hooks for their extensive React component tests. `beforeEach` is commonly used to mount components in a clean JSDOM environment, while `afterEach` ensures proper unmounting and cleanup, critical for preventing memory leaks and test pollution in large-scale UI testing.