Making Tests Readable
What you'll learn: How to write tests that clearly communicate what is being tested, why, and what the expected outcome is—making them readable as living documentation.
Why Test Readability Matters
You've learned to structure tests with AAA, focus on one thing, avoid logic, and make them self-documenting. Now let's tie it all together: a readable test should read almost like a specification or a plain-English statement about your system's behavior.
When someone reads your test (including future-you), they should instantly understand:
- What scenario is being tested
- What action triggers the behavior
- What outcome is expected
Writing Tests That Read Like Specifications
Think of your test as a sentence: "When [scenario], then [outcome]." Use descriptive test names and clear variable names that tell the story:
// ❌ Hard to understand
test('test1', () => {
const x = new Calculator();
const r = x.add(2, 2);
expect(r).toBe(4);
});
// ✅ Reads like a specification
test('add returns sum of two positive numbers', () => {
const calculator = new Calculator();
const sum = calculator.add(2, 2);
expect(sum).toBe(4);
});
Notice how the second version tells you exactly what input (two positive numbers) produces what output (their sum) under what conditions (calling add). Someone unfamiliar with your code can read this test and understand the calculator's behavior without looking at the implementation.
Use whitespace (blank lines between Arrange-Act-Assert), meaningful names, and avoid abbreviations. Your test should be so clear that comments are rarely needed.
Key Takeaway: Write tests that read like plain-English specifications—clear names, obvious inputs and outputs, and structure that tells the story of what behavior you're verifying.