patternMinorpending
Testing error paths — asserting that code throws
Viewed 0 times
toThrowrejectspytest.raiseserror testingassert throwsexpect error
nodejsbrowser
Problem
Test needs to verify that a function throws an error, rejects a promise, or returns an error response. Writing expect(throwingFn()).toThrow() doesn't work because the error escapes.
Solution
Wrap the call in an arrow function. Jest/Vitest: expect(() => throwingFn()).toThrow('message'). For async: await expect(asyncFn()).rejects.toThrow('message'). For specific error types: expect(() => fn()).toThrow(TypeError). Python pytest: with pytest.raises(ValueError, match='pattern'): fn(). For HTTP APIs: expect the status code and error body separately. Common mistake: expect(throwingFn()).toThrow() calls the function immediately — the error escapes before expect() can catch it. The arrow function wrapper defers execution.
Why
expect() needs a function reference to call, not the result of calling. If you call the function directly, the exception propagates before Jest can intercept it.
Revisions (0)
No revisions yet.