Setup and Teardown: beforeEach and afterEach
You'll learn how to run preparatory and cleanup code automatically around each test, keeping your tests isolated and independent.
Why Setup and Teardown Matter
Imagine you're testing a shopping cart object. Each test needs a fresh, empty cart to work with, and after the test runs, you might need to clean up database connections or reset global state. Doing this manually in every single test would be repetitive and error-prone.
That's where beforeEach and afterEach hooks come in. They're special functions that run automatically before and after each test case (each it block) within a describe block.
How They Work
beforeEach() runs before each test, letting you set up a clean starting state. afterEach() runs after each test completes, letting you tear down or reset anything that changed.
describe('Shopping Cart', () => {
let cart;
beforeEach(() => {
// Runs before EACH test
cart = { items: [], total: 0 };
});
afterEach(() => {
// Runs after EACH test
cart = null; // cleanup
});
it('should start empty', () => {
// cart is fresh from beforeEach
console.log(cart.items.length === 0); // true
});
it('should add items correctly', () => {
// cart is fresh AGAIN from beforeEach
cart.items.push('apple');
console.log(cart.items.length === 1); // true
});
});
Each test gets its own fresh cart object, preventing tests from interfering with each other. This isolation is crucial for reliable, maintainable test suites.
Think of It As
It's like a restaurant kitchen: before each dish (beforeEach), you prep a clean workspace; after each dish (afterEach), you wipe down and reset for the next order.
Key Takeaway: Use beforeEach() and afterEach() hooks to automatically prepare and clean up state around each test, ensuring every test runs in isolation with a predictable starting point.