Custom error messages with Jest for assertions
This is what I tell the computer sometimes, out loud. That's not weird.

Custom error messages with Jest for assertions

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.

No alt text provided for this image

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

Unclear error 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 ????

use `throw new 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 :)

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

Ehab ELFEKI

DevOps Engineer@ORIS

3 年

this is so funny! I was having the same idea and found this post here, really nice :D

Cameron Elliot

Software Developer at Centerprise Services Ltd

3 年

Late to the party here, but this solution is problematic. The exception could be caused by any number of things, not just your assertion that "doesn't contain prop '${prop}'". It may be that demoVersion is null/undefined/not an array. It may be that demoVersions is an empty array. It may be that demoVersions[0] is null/undefined. But in each of these cases the error message is misleading the developer into thinking the problem is something else.

What a smart way to create more meaningful error logs when testing!

要查看或添加评论,请登录

Aart den Braber的更多文章

社区洞察

其他会员也浏览了