Testing Error Handling

Learn how to properly test error handling and error messaging in our JavaScript applications using Jest.

While testing our code for the expected results is important, it is also necessary to test it to handle unexpected situations (errors and exceptions). We can do this by testing the throw itself or by testing the error thrown.

Testing the throw

Jest natively supports testing whether or not a function has thrown an error. To accomplish this, we use one of the two matchers below.

  • .toThrow()
  • .toThrowError()

Note: .toThrowError() is really just an alias of .toThrow() and comes down to personal preference.

There is a very specific way these two need to be called. We can call a function directly inside expect, but we must call it inside an anonymous function:

const errFunc = () => {
  throw new Error('Error!');

expect(() => errFunc()).toThrow();

If we were to call it like expect(errFunc()).toThrow(), the error would throw, but that would fail our tests, which is the opposite of what we want.

Get hands-on with 1200+ tech skills courses.