Chapter 2 · Practice 1 of 5
Structure every test as Arrange, Act, Assert
Why it matters
Every test does three things: set up the inputs, call the code under test, and check the result. Making those three phases visible, with a blank line between them, means anyone can read a test at a glance. Some teams call the same phases given, when, then.
- Arrange: build the inputs and any collaborators the code needs.
- Act: make one call to the thing you are testing.
- Assert: check the result or the side effect.
If the Act phase has several calls, you are probably testing more than one behaviour. If the Arrange phase is 40 lines long, the code under test may have too many dependencies, or you need a small helper or fixture that builds valid test data.
Example
import { describe, it, expect } from 'vitest';
import { applyDiscount } from './pricing';
describe('applyDiscount', () => {
it('takes 10 percent off orders of 100 or more', () => {
// Arrange
const order = { subtotal: 120, items: 3 };
// Act
const total = applyDiscount(order);
// Assert
expect(total).toBe(108);
});
});