Unused test setup: beforeEach without cleanup
Quick summary
Your beforeEach creates resources but there is no afterEach to clean up — subsequent tests are affected by leftover state.
Why this happens
beforeEach creates a database record or file but afterEach does not delete it
Setup modifies global state that is never restored after the test
A test server is started in beforeAll but not stopped in afterAll
Minimal example
beforeEach(async () => {
await db.query('INSERT INTO users (id, name) VALUES (1, "test")');
// no afterEach — user record pollutes subsequent tests
});
test('counts users', async () => {
const count = await db.query('SELECT COUNT(*) FROM users');
expect(count).toBe(1); // fails if other tests added users
});beforeEach(async () => {
await db.query('INSERT INTO users (id, name) VALUES (1, "test")');
});
afterEach(async () => {
await db.query('DELETE FROM users'); // cleanup
});
test('counts users', async () => {
const count = await db.query('SELECT COUNT(*) FROM users');
expect(count).toBe(1); // always 1 — clean state
});Adding afterEach to delete the user record ensures each test starts with a clean database, preventing state pollution.
How to diagnose
Review beforeEach/beforeAll hooks and check for matching afterEach/afterAll cleanup
Run tests in different orders to detect if leftover state affects results
Check for resources (files, database records, ports) that accumulate across tests
How to fix
Add afterEach or afterAll hooks that clean up all resources created in setup
Use a transaction that rolls back after each test instead of creating and deleting records
Stop servers and close connections in afterAll that were started in beforeAll
How to prevent
Always pair setup hooks with cleanup hooks: beforeEach with afterEach, beforeAll with afterAll
Use test databases with automatic cleanup or transaction rollback for database tests
Related Resources
Related Glossary
Related Lessons
- Test Setup
Learn about cleanup.