Setup and Teardown
In one line
Setup (beforeEach/beforeAll) prepares the environment before tests; teardown (afterEach/afterAll) cleans up after.
In simple words
Setup and teardown functions handle the repetitive parts of testing that aren't the actual test logic.
Setup runs before tests to prepare the environment:
- Create test data
- Initialize variables
- Connect to a test database
- Mock dependencies
Teardown runs after tests to clean up:
- Reset variables
- Close database connections
- Restore mocks
- Clear timers
In Jest, the hooks are:
beforeEach/afterEach— run before/after every single testbeforeAll/afterAll— run once before/after all tests in the suite
Using these hooks keeps your tests DRY (don't repeat yourself) and ensures each test starts with a clean state.
Example
javascript
beforeEach(() => {
// Setup: fresh data before each test
users = [{ id: 1, name: 'Alice' }];
});
afterEach(() => {
// Teardown: clean up after each test
jest.clearAllMocks();
});beforeEach creates fresh data; afterEach cleans up mocks after every test.
Related terms
Related Resources
Related Lessons
- Setup and Teardown
Test hooks for setup and cleanup.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.