Using Test Setup and Teardown Methods
You'll learn how to use setup and teardown hooks to eliminate duplicate test code while keeping each test independent.
The Core Idea
When multiple tests need the same initial state or cleanup, you can extract that common work into setup (runs before each test) and teardown (runs after each test) methods. This is like resetting a game board before each player's turn—everyone starts from the same clean state without repeating the reset instructions every time.
Setup and teardown methods reduce duplication in your Arrange phase while ensuring tests don't affect each other.
When to Use Setup/Teardown
Use setup when several tests need:
- The same objects initialized
- The same test data created
- The same state prepared
Use teardown when tests need:
- Resources closed (files, connections)
- Temporary data cleaned up
- Side effects undone
Example Structure
class UserServiceTest {
setup() {
// Runs before EACH test
this.database = createTestDatabase();
this.userService = new UserService(this.database);
}
teardown() {
// Runs after EACH test
this.database.close();
}
testCreateUser() {
// Arrange already done in setup
// Act
const user = this.userService.create("Alice");
// Assert
assert(user.name === "Alice");
}
testDeleteUser() {
// Fresh setup runs automatically
const user = this.userService.create("Bob");
// Act
this.userService.delete(user.id);
// Assert
assert(this.userService.find(user.id) === null);
}
}
Each test gets a fresh database and userService automatically—no shared state between tests.
Avoiding Setup Overuse
Don't put everything in setup. Only extract common arrangements that most tests need. Test-specific setup stays in the test itself for clarity.
Key Takeaway: Setup and teardown methods eliminate repetitive test preparation and cleanup code while guaranteeing each test starts with a clean, independent state.