πŸ’‘ This page contain affiliate links. By making a purchase through them, we 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 β€’ πŸ“– 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:

const functionWithError = param => {  
    throw new Error()
}

it('should throw an error', () => {
    expect(functionWithError).toThrow(Error)
})
Copied to clipboard!

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

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

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')
})
Copied to clipboard!
How to Mock process.env in Jest
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended