Assertion Throw
Question
How do you test that a function throws an error?
Hint
toThrow verifies the function throws when called.
Explanation
In Jest, expect(() => fn()).toThrow() tests that fn throws an error. Variants: toThrow("specific message") checks the error message. toThrow(ErrorClass) checks the error type. toThrowInstanceOf(ErrorClass) is an alias. The function must be wrapped in a callback — expect(fn()) would call fn before expect can catch the error. For async: await expect(asyncFn()).rejects.toThrow("error"). Testing error cases is important — errors are part of the API contract. Test both that errors are thrown and that they have the right type/message for debugging.
Related Resources
Related Lessons
- Assertions
Learn assertions.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.