Test Organization Patterns: AAA and Given-When-Then
You'll learn: How to structure individual test cases using two proven patterns that make your tests readable, maintainable, and self-documenting.
The Core Idea
Even with proper describe and it blocks, the code inside each test can become messy. Two patterns help organize test logic: AAA (Arrange-Act-Assert) and Given-When-Then. They're actually the same concept with different names—one from programming, one from behavior-driven development.
Both patterns divide a test into three clear sections:
- Arrange/Given: Set up the preconditions and inputs
- Act/When: Execute the behavior you're testing
- Assert/Then: Verify the outcome matches expectations
Think of it like a science experiment: prepare your materials (arrange), perform the experiment (act), and record the results (assert).
AAA Pattern in Practice
describe('calculateDiscount', () => {
it('should apply 20% discount to premium members', () => {
// Arrange
const user = { membershipLevel: 'premium' };
const orderTotal = 100;
// Act
const finalPrice = calculateDiscount(user, orderTotal);
// Assert
assert.strictEqual(finalPrice, 80);
});
});
Given-When-Then Pattern
The BDD-style naming emphasizes the scenario:
describe('Shopping Cart', () => {
it('should remove item when quantity reaches zero', () => {
// Given a cart with one item
const cart = new ShoppingCart();
cart.addItem('apple', 1);
// When I remove that item
cart.removeItem('apple');
// Then the cart should be empty
assert.strictEqual(cart.itemCount(), 0);
});
});
Use comments or whitespace to visually separate the sections. This makes tests scannable—you can instantly understand the setup, action, and expectation.
Key Takeaway: Structure every test with Arrange-Act-Assert (or Given-When-Then) to create self-documenting tests where setup, execution, and verification are clearly separated.