Suite-Level Setup: beforeAll and afterAll
You'll learn when to use suite-level hooks to run expensive setup operations once instead of repeating them before every test.
Why Suite-Level Hooks Exist
While beforeEach and afterEach run around every individual test, sometimes you have setup operations that are too expensive to repeat dozens of times. Think of starting a database connection, spinning up a test server, or loading a large dataset into memory. If these operations are slow but their state doesn't change between tests, you're wasting time and resources running them repeatedly.
The Core Idea
beforeAll() runs once before any tests in the suite execute. afterAll() runs once after all tests complete. They're your suite-level bookends for expensive operations that can be shared across tests.
describe('Database queries', () => {
beforeAll(() => {
// Connect to database once
db.connect();
console.log('Connected to database');
});
afterAll(() => {
// Clean up once after all tests
db.disconnect();
console.log('Disconnected from database');
});
it('should fetch user data', () => {
const user = db.getUser(1);
expect(user.name).toBe('Alice');
});
it('should fetch post data', () => {
const posts = db.getPosts();
expect(posts.length).toBeGreaterThan(0);
});
});
When to Use Them
Use beforeAll and afterAll when:
- Setup is expensive (time or resources)
- Tests don't modify the shared state
- You need global test fixtures available throughout the suite
Avoid them when tests mutate shared state—each test might affect the next, creating unpredictable failures.
Key Takeaway: Use beforeAll() and afterAll() for expensive, once-per-suite setup that remains unchanged across tests, saving time while maintaining reliable test execution.