Custom error messages with Jest for assertions

Aart den Braber
3 min readJan 9, 2021

While writing an application in Node, I was trying to test whether an object had certain properties (by lack of TypeScript, because this was a a very simple application).

The (now simplified) test looked like this.

At a certain point, this test failed, and this was my error message:

Unclear error message: undefined
A pretty non-helpful message

This doesn’t seem too bad, but there’s no way for me to know which property throws the error, as it’s looping over the required properties. So what is a poor developer to do? Adding a custom message, of course — with the faulty prop displayed inside! I want to see something like “ Doesn’t contain prop ‘version’ “. That shouldn’t be too hard.

However, as discussed in these posts, it apparently is:

It seems to be something that Jest’s creators overlooked.

The solution

First, you need to know that Jest’s `expect`-function throws an error when things don’t turn out as expected. This means that you can catch this error and do something with it.

add a try-catch block with a `console.error()` inside

And this works as we want! You can see the text which identifies the culprit. A great thing.

message is showing, but the test is passing

However, the test is passing, which is a bad thing for CI/CD, where tests are automated and prevent malformed code to reach the customer. Because of this, you need to let Jest know that something went wrong, and that the test should fail instead.

This is easy though. You can simply throw another error 👍🏈

add a try-catch block with a `console.error()` inside
Throw the error 🏈

…which works like a charm. You both get a nice message and the test fails as well.

message is showing and the test is FAILING :)
The message is showing and the test is FAILING :)

I hope this helped you, leave a message if you want!

Also, if you’re looking for a new job, Ordina is genuinely an amazing company. If you’re interested, you can send me a message. 👍😁

--

--

Aart den Braber

Software developer with a passion for beautiful code