Custom error messages with Jest for assertions
Aart den Braber
Ik ben een freelance dev bij DUO met een passie voor mooie code en onderhoudbare applicaties
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:
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.
And this works as we want! You can see the text which identifies the culprit. A great thing.
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 ????
...which works like a charm. You both get a nice message and the test fails as well.
I hope this helped you, leave a message if you want!
DevOps Engineer@ORIS
3 年this is so funny! I was having the same idea and found this post here, really nice :D
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.
Practice Lead
4 年What a smart way to create more meaningful error logs when testing!