jest: expect tothrow

2021-07-24

 | 

~2 min read

 | 

351 words

When testing code that you expect to fail with Jest, you need to wrap the function. This is called out explicitly in the docs.

Note: You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail.

However, since it’s different from how most of the other APIs work (and intellisense doesn’t help here), it’s easy to overlook!

expect to throw

Even more confusingly, the error is often exactly where you’re looking for it - that’s why you wrote the test in the first place.

What does it mean to wrap the code in a function? There are a few different ways to do that:

  1. Define a new function at the top of your test which is then passed to the expect call as an argument.
  2. Use an anonymous lambda expression within the expect.

The former is what’s shown in the docs, but for completeness sake, let’s compare.

Imagine a quick data check function that will throw if important fields are missing:

helper.ts
const MISSING_FIELD_ERROR = "Required field is missing"
function validateData(data: any) {
  const { title } = data
  if (!title) {
    throw new Error(MISSING_FIELD_ERROR)
  }
  return { title }
}

Now, we want to write a test to make sure it throws an error if we try to pass some data that’s missing a title key.

If we take the approach of defining a new wrapped function (as the docs demonstrate), it might look like this:

helper.test.js
it("will throw an error if required information is missing", () => {
  const missingTitle = {
    file: {},
  }
  const wrappedValidateData = () => {
    validateData(missingTitle)
  }
  expect(wrappedValidateData).toThrowError(MISSING_FIELD_ERROR)
})

Alternatively, we can use a lambda inside of our expect function:

helper.test.js
it("will throw an error if required information is missing", () => {
  const missingTitle = {
    file: {},
  }
  expect(() => validateData(missingTitle)).toThrowError(MISSING_FIELD_ERROR)
})

While the latter is terser, the former has the advantage that if you have multiple expect calls in a given it block, you will only have to define it once using the wrapped approach.


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!