Write Good Test Assertions
Writing good assertions is critical as they validate whether the behavior of the code meets expectations—not just today, but for as long as the software lives. Let’s get into what makes a good test assertion.
The Structure of a Clean Test
You should structure every test into three key sections: Setup, Exercise, and Assert. In the Setup section, you prepare the necessary environment, initialize objects, and configure any prerequisites required for the test. The Exercise section involves executing the actual code or functionality that you intend to test. Finally, the Assert section is where you verify the outcomes by comparing the actual results with expected values, ensuring the code behaves as intended.
Good assertions are specific, clear to read, declarative, and directly linked to the expected behavior, making it easier to identify and diagnose issues.
Writing Good Assertions
Every test must have a single clear assertion.
Consider this JavaScript example:
test('should add two numbers', () => {
const result = add(2, 3);
// No assertions to verify the result
});
This test doesn’t verify any outcomes. It calls a function but doesn’t check if the result is correct but many test runners will flag them as “risky.”
Test a Single Responsibility at Once
Tests should have a single responsibility and a clear reason to fail.
This is a test with multiple responsibilities:
test('should add ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access