Writing Self-Documenting Tests
You'll learn: How to write tests that clearly explain their purpose and behavior without requiring additional comments.
The Core Idea
Self-documenting tests act as living documentation for your code. When someone reads your test (including future you), they should immediately understand what is being tested, why it matters, and what behavior is expected—all without hunting for explanatory comments.
Think of it like a good restaurant menu: instead of "Item #5," you see "Grilled Salmon with Lemon Herb Butter." The name tells you exactly what you're getting.
Descriptive Test Names
Your test name should read like a sentence describing the behavior being verified:
Bad: test1(), testUserMethod(), checkValidation()
Good: calculatesDiscountWhenCustomerIsVIP(), rejectsOrderWhenInventoryIsInsufficient(), returnsEmptyListWhenNoMatchesFound()
Use the format: action_condition_expectedResult or methodName_whenCondition_thenExpectedResult.
Clear Assertions
Your assertions should reveal what you're verifying. Choose assertion methods that express intent:
Less clear:
assert(result === true); // What does true mean here?
More clear:
assertIsAuthenticated(result); // Obvious what we're checking
When using generic assertions, name your variables descriptively:
const expectedTotalPrice = 150;
const actualTotalPrice = cart.calculateTotal();
assertEqual(actualTotalPrice, expectedTotalPrice);
The variable names make the assertion self-explanatory—no comment needed to say "checking the total price."
Why This Matters
Self-documenting tests serve as examples of how your code should work. When tests fail, clear names and assertions help you diagnose issues faster. They also help new team members understand system behavior by reading tests.
Key Takeaway: Write test names that describe the exact behavior being verified and use clear variable names and assertions that make the expected outcome obvious—your tests should tell a story without requiring comments.