Avoiding False Positives with Assertions
You'll learn how to ensure your async tests truly validate behavior instead of silently passing when they shouldn't.
The Hidden Danger of "Passing" Tests
A false positive occurs when a test passes, but not because your code is correct—rather, the assertions never actually ran. This is especially common in async tests where timing issues or unhandled promise rejections cause test code to complete before assertions execute.
Think of it like a fire alarm test where you press the button but forget to check if sound comes out. The test "completes" without actually verifying anything.
Common Pitfalls
Forgotten return statements: If you don't return a promise or use await, the test finishes before async assertions run:
// BAD: Test completes before fetch finishes
it('fetches user data', () => {
fetchUser(1).then(user => {
expect(user.name).toBe('Alice'); // Never runs!
});
// Test exits immediately
});
// GOOD: Promise returned, assertions waited for
it('fetches user data', () => {
return fetchUser(1).then(user => {
expect(user.name).toBe('Alice'); // Runs before test completes
});
});
Unhandled rejections: If a promise rejects but you don't handle it properly, assertions in the rejection path may never execute, causing tests to pass incorrectly.
Dangling callbacks: With callback-based APIs using the done() pattern, forgetting to call done() or calling it too early can skip assertions.
Prevention Strategies
Always verify your async tests with intentional failures first—temporarily break your code and confirm the test fails. If it still passes, your assertions aren't running. Use proper promise handling (return or await), and leverage your test runner's timeout features to catch tests that never complete.
Key Takeaway: False positives are worse than false negatives—always verify your async assertions actually execute by testing the failure case first.