πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.
How to Correctly Expect an Error in Jest

How to Correctly Expect an Error in Jest

Testing try catch errors
Ferenc Almasi β€’ 2022 June 28 β€’ Read time 2 min read
  • twitter
  • facebook

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:

Copied to clipboard! Playground
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:

Copied to clipboard! Playground
// 🟒 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:

Copied to clipboard! Playground
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)
Pass the correct type of error to test different types

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:

Copied to clipboard! Playground
const functionWithError = () => {
    throw new TypeError('Custom Error')
}

it('should throw an error', () => {
    expect(functionWithError).toThrow(TypeError)
    expect(functionWithError).toThrow('Custom Error')
})
How to Mock process.env in Jest
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.