Truthiness and Falsiness Assertions
You'll learn how to explicitly test for truthy, falsy, null, and undefined values in your test assertions.
Why Explicit Truthiness Matters
When testing JavaScript code, you often need to verify not just exact values, but whether something exists, is defined, or evaluates to true/false in a boolean context. Rather than using loose equality or converting values manually, test frameworks provide dedicated assertions for these common scenarios.
The Core Assertions
Most test frameworks offer these specific matchers:
Truthiness checks:
expect(value).toBeTruthy(); // Passes if value is truthy (non-zero, non-empty, true, etc.)
expect(value).toBeFalsy(); // Passes if value is falsy (0, '', false, null, undefined, NaN)
Explicit null/undefined checks:
expect(value).toBeNull(); // Only passes for null
expect(value).toBeUndefined(); // Only passes for undefined
expect(value).toBeDefined(); // Passes for anything except undefined
When to Use Each
- Use
toBeTruthy()when you care that something exists, but not its exact value - Use
toBeFalsy()when testing error conditions or empty states - Use
toBeNull()when explicitly checking for intentional null assignments - Use
toBeUndefined()when verifying a variable hasn't been initialized - Use
toBeDefined()when ensuring a function returned anything other than undefined
Think of these as semantic assertions: they communicate intent better than expect(value === true) or expect(!value). When someone reads toBeDefined(), they immediately understand you're checking for existence, not a specific value.
Key Takeaway: Use dedicated truthiness assertions (toBeTruthy, toBeFalsy, toBeNull, toBeUndefined) to make your test intentions explicit and your code more readable than manual boolean conversions.