Exception Assertions
What you'll learn: How to verify that functions throw the expected errors when they should, ensuring your error-handling code works correctly.
Why Test for Errors?
Not all code paths succeed. Sometimes functions should throw errors—when given invalid input, when preconditions aren't met, or when operations fail. Exception assertions let you test these failure scenarios explicitly, ensuring your code fails gracefully and predictably.
Think of it like testing a smoke alarm: you don't just check if it stays quiet during normal conditions; you also verify it sounds when there's actual smoke.
The toThrow Matcher
Most test runners provide a toThrow (or throws) assertion that checks whether a function throws an error when executed:
function divide(a, b) {
if (b === 0) {
throw new Error('Cannot divide by zero');
}
return a / b;
}
// Test that the function throws
it('should throw when dividing by zero', () => {
expect(() => divide(10, 0)).toThrow();
});
Critical detail: You must wrap the function call in an arrow function. Passing divide(10, 0) directly would throw before the assertion runs.
Asserting Specific Error Messages
You can verify the exact error message or error type:
it('should throw with specific message', () => {
expect(() => divide(10, 0)).toThrow('Cannot divide by zero');
});
it('should throw specific error type', () => {
expect(() => divide(10, 0)).toThrow(Error);
});
This ensures you're not just catching any error, but the right error for the right reason.
Key Takeaway: Use toThrow() to test that functions throw expected errors, always wrapping the call in an arrow function so the assertion can catch the exception instead of letting it escape your test.