Choosing the Right Assertion
You'll learn how selecting specific versus general assertions improves test clarity and makes failures easier to diagnose.
The Power of Precision
When writing tests, you could technically use toBe(true) for everything by wrapping logic in conditionals, but that's like using only a hammer when you have a full toolbox. The right assertion tells future readers (including yourself) what you're actually testing and produces helpful error messages when things break.
Specific vs General Assertions
General assertions like toBe() or toEqual() work for many scenarios but give vague feedback:
expect(user.age > 18).toBe(true); // What was the actual age?
Specific assertions express intent clearly and provide context:
expect(user.age).toBeGreaterThan(18); // Failure shows: "Expected 16 to be > 18"
Decision Guidelines
- For numbers: Use
toBeGreaterThan(),toBeLessThan(),toBeCloseTo()instead of manual comparisons - For strings: Use
toContain()ortoMatch()instead of testingstring.includes() - For arrays: Use
toContain()ortoHaveLength()instead of checking properties manually - For exceptions: Use
toThrow()instead of try-catch blocks with boolean flags - For existence: Use
toBeDefined(),toBeNull()instead oftoBe(undefined)
Why It Matters
Specific assertions are self-documenting. When toHaveLength(3) fails, the error shows expected vs actual length immediately. When toBe(true) fails on array.length === 3, you only know something was false—requiring you to debug which part failed.
Key Takeaway: Choose the most specific assertion that matches your intent; it documents what you're testing and provides actionable failure messages that speed up debugging.