Setup and Teardown
If you find yourself writing the same setup code in every test, something is wrong. Jest gives you hooks that run before and after your tests so you can keep things DRY. Let me give you the rundown.
One thing that confused me at first was the difference between beforeEach and beforeAll. It matters more than you think.
beforeEach - Run Before Every Test
This runs before each it() or test() in the current describe block. Use it to set up fresh data for every test.
let user;
beforeEach(() => {
user = { name: 'Alice', score: 0 };
});
it('starts with score 0', () => {
expect(user.score).toBe(0);
});
it('increments score', () => {
user.score += 10;
expect(user.score).toBe(10);
});
Each test gets a fresh user object. That is important because tests should not depend on each other.
afterEach - Run After Every Test
This runs after each test. Use it to clean up anything you created during the test.
let spy;
afterEach(() => {
if (spy) spy.mockRestore();
});
it('spies on console.log', () => {
spy = jest.spyOn(console, 'log').mockImplementation(() => {});
console.log('test');
expect(spy).toHaveBeenCalled();
});
beforeAll and afterAll
These run once before all tests and once after all tests in the block. Use them for expensive operations like setting up a database connection.
let db;
beforeAll(async () => {
db = await connectToDatabase();
});
afterAll(async () => {
await db.close();
});
it('queries users', async () => {
const users = await db.getUsers();
expect(users.length).toBeGreaterThan(0);
});
Order of Execution
Jest runs hooks in this order: beforeAll, then for each test: beforeEach, test, afterEach, and finally afterAll. Understanding this helps you debug when setup goes wrong.
Try it Yourself →Key Takeaways
- beforeEach runs before every test, perfect for fresh test data
- afterEach runs after every test, good for cleanup
- beforeAll runs once before all tests, good for expensive setup
- afterAll runs once after all tests, good for cleanup like closing connections
- Keep test setup in hooks so tests stay focused and DRY