The Given-When-Then Pattern
You'll learn: How to structure test method bodies using the Given-When-Then pattern to make tests read like specifications.
What It Is
The Given-When-Then pattern is a way of organizing test code that mirrors how we naturally describe scenarios. It divides your test into three clearly labeled sections:
- Given (setup): The initial state or context
- When (action): The specific action being tested
- Then (assertion): The expected outcome
This is essentially the AAA pattern (Arrange-Act-Assert) you already know, but with more narrative-friendly labels that read like plain English specifications.
Why It Helps
Think of it like telling a story: "Given I have 20, then I should have $30 remaining." This structure makes tests incredibly readable, especially for business stakeholders or when tests serve as living documentation.
The pattern works beautifully when tests describe behavior from a user or business perspective. You might use actual comments or just organize your code with these phases in mind:
test('withdraw reduces account balance') {
// Given: an account with $50
const account = new Account(50);
// When: withdrawing $20
account.withdraw(20);
// Then: balance should be $30
assertEqual(account.balance, 30);
}
The comments aren't always necessary once your team is familiar with the pattern, but they can help during the transition or in complex scenarios.
When to Use It
Given-When-Then shines in behavioral and acceptance tests where you're describing user scenarios. For lower-level unit tests, the simpler AAA terminology might feel more natural.
Key Takeaway: Given-When-Then structures tests as readable specifications by explicitly labeling the setup, action, and assertion phases with narrative-friendly language.