
How to Correctly Expect an Error in Jest
Whenever you are looking to test an error thrown by a function in Jest, you want to pass the function to the expect
, rather than invoking the function. Take a look at the following examples:
const functionWithError = param => {
throw new Error()
}
it('should throw an error', () => {
expect(functionWithError).toThrow(Error)
})
We have a mock function and we want to test whether it throws the error we are expecting. We can do this by simply passing the function to the expect without actually invoking it, and calling theΒ toThrow
Β method on it with the passed error.
But what if you have to call the function, for example, to provide parameters? In this case, you can wrap the function into an anonymous function:
// π’ Do
expect(() => functionWithError()).toThrow(Error)
// π΄ Donβt
expect(functionWithError()).toThrow(Error)
expect(functionWithError('param')).toThrow(Error)
Notice that if you try to call the function directly inside the expect
, it will fail the test as the error is not caught and the assertion will fail. You can also test other types of errors by passing the correct error to toThrow
:
expect(functionWithError()).toThrow(EvalError)
expect(functionWithError()).toThrow(RangeError)
expect(functionWithError()).toThrow(ReferenceError)
expect(functionWithError()).toThrow(SyntaxError)
expect(functionWithError()).toThrow(TypeError)
expect(functionWithError()).toThrow(URIError)
expect(functionWithError()).toThrow(AggregateError)
Lastly, if you would like to test the error message itself, toThrow
also accepts a string so you can test both the type and message:
const functionWithError = () => {
throw new TypeError('Custom Error')
}
it('should throw an error', () => {
expect(functionWithError).toThrow(TypeError)
expect(functionWithError).toThrow('Custom Error')
})

Unlimited access to hundred of tutorials
Access to exclusive interactive lessons
Remove ads to learn without distractions