Search⌘ K

Testing Error Handling

Explore how to effectively test error handling in JavaScript code using Jest. Learn to use native matchers such as toThrow and toThrowError, test specific error messages, apply try/catch blocks, and implement snapshot testing to ensure your functions handle exceptions correctly.

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 ...