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!
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:
expect
call as an argument.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:
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:
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:
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!