What beforeEach() and afterEach() Do
beforeEach() registers a function that Jest runs before every single test within its scope, while afterEach() registers a function that runs after every single test. Together they let you establish a known starting state and reliably clean up afterward, so tests don't accidentally depend on leftover state from a previous test.
Cricket analogy: Think of beforeEach() like the groundstaff rolling and re-marking the pitch before every single delivery in a net session—Virat Kohli gets a freshly prepared surface each time so no ball is affected by footmarks from the last one.
Setting Up Fresh State with beforeEach()
A typical beforeEach() creates a brand-new instance of the class or component under test, resets mocks with jest.clearAllMocks(), and reinitializes any mock dependencies like a fake database client. This guarantees that no test's assertions are influenced by mutations another test made earlier in the file.
Cricket analogy: Using beforeEach() to instantiate a new UserService() before each test is like a bowling coach handing Jasprit Bumrah a brand-new ball before each over rather than a scuffed one carried over from the last over.
describe('UserService', () => {
let service;
let mockDb;
beforeEach(() => {
mockDb = { save: jest.fn(), find: jest.fn() };
service = new UserService(mockDb);
});
afterEach(() => {
jest.restoreAllMocks();
mockDb = null;
});
test('creates a user', () => {
service.create({ name: 'Asha' });
expect(mockDb.save).toHaveBeenCalledWith({ name: 'Asha' });
});
test('does not call save twice on init', () => {
expect(mockDb.save).not.toHaveBeenCalled();
});
});Cleaning Up with afterEach()
afterEach() is where you undo whatever setup or side effects a test may have left behind: restoring spies with jest.restoreAllMocks(), switching back to real timers with jest.useRealTimers(), or closing open file handles and network connections opened during the test.
Cricket analogy: afterEach() calling jest.restoreAllMocks() is like the umpire changing the ball and resetting the over count after Mohammed Shami's spell ends, wiping the slate so the next bowler isn't judged on stale figures.
Forgetting afterEach(() => jest.restoreAllMocks()) after using jest.spyOn() is a common source of flaky tests — a spy or mock installed in one test can silently leak into unrelated tests that run afterward in the same file.
Scoping Hooks Within describe() Blocks
Hooks declared inside a nested describe() block only apply to the tests within that block and any blocks nested inside it. When hooks are nested, Jest runs outer beforeEach() hooks before inner ones, and runs inner afterEach() hooks before outer ones, mirroring how the blocks themselves are nested.
Cricket analogy: Nested beforeEach() hooks running outer-then-inner is like a team's fielding drill where the head coach's general warm-up runs before the specialist wicketkeeping coach's drill for MS Dhoni, in that fixed order.
Hooks can be async — Jest supports returning a promise or using an async function for beforeEach()/afterEach(), and it will wait for that promise to resolve before proceeding to the test or the next hook. Legacy callback-based hooks using a done argument are still supported but async/await is preferred.
- beforeEach() runs before every test in its describe scope; afterEach() runs after every test.
- Use beforeEach() to create fresh mocks, instances, or state so tests don't depend on execution order.
- Use afterEach() to restore mocks, clear timers, and release resources opened during a test.
- Hooks nested inside a describe() block only apply to tests within that block and its children.
- Outer beforeEach() hooks run before inner ones; inner afterEach() hooks run before outer ones.
- Hooks can be async — return a promise or use async/await and Jest will wait.
- Not resetting mocks between tests is a leading cause of flaky, order-dependent test suites.
Practice what you learned
1. What is the primary purpose of beforeEach() in Jest?
2. In nested describe blocks, what is the execution order of beforeEach() hooks?
3. Which hook is most appropriate for restoring mocks with jest.restoreAllMocks() after each test?
4. What happens if a beforeEach() hook returns a rejected promise?
5. Why might you scope a beforeEach() inside a nested describe() rather than at the top level?
Was this page helpful?
You May Also Like
beforeAll() and afterAll()
Understand how Jest's beforeAll() and afterAll() hooks handle one-time, expensive setup and teardown shared across an entire test suite.
Test Fixtures and Factories
Learn how to build reusable test fixtures and factory functions to generate consistent, customizable test data across a Jest suite.
Testing React Components with React Testing Library
Learn how to test React components the way a user experiences them, using render, screen queries, userEvent, and async assertions.