6 stages of refactoring a Jest test case

Written by:
wordpress-sync/Screen-Shot-2019-09-04-at-10.20.00

September 4, 2019

0 mins read

An underrated feature of Jest is customizing the way assertion errors that the console displays when tests fail are handled. Imagine the following test code, which needs to programmatically loop an object in order to ensure keys exist as expected (using the expect function):

jest1

The test is written fine. Now, imagine what happens if a developer on the team makes some changes to the code: adds a new file in one part and forgets to add it to another important part of the same project, such as ensuring it is exported correctly.

The next time the test runs, it will fail. However, the reason won't be obvious to most; and if you’re new to the code, you're likely not even to know what broke. Give it a try:

jest2

So for that reason, Jest also requires using a toHaveProperty() with expect, which looks like this:

jest3

Now when a test fails it at least makes it clearer as to which property is missing. However, it’s still a bit cryptic as you can see in the next screenshot. What can we do? ?

jest4

At this point, it might be good enough with the annotations that are there already. The test name is self-explanatory, as you can see. But we only have one test case that fails, and when looking at a test trace, we can't clearly evaluate which validators were used.

Let's refactor the code:

jest5

Now, when my test passes or fails, it is much more obvious and intuitive as to what exactly was tested, what exactly failed, and why:

jest6

Much better! ???


If you love Jest as much as I do (?) you might also be interested in reading some of my other pieces on Jest:

If you're into web security as well, I'd love to meet you on The Secure Developer slack community, or on Twitter if that's more your thing.

Posted in:Engineering
Patch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo Segment

Snyk is a developer security platform. Integrating directly into development tools, workflows, and automation pipelines, Snyk makes it easy for teams to find, prioritize, and fix security vulnerabilities in code, dependencies, containers, and infrastructure as code. Supported by industry-leading application and security intelligence, Snyk puts security expertise in any developer’s toolkit.

Start freeBook a live demo

© 2024 Snyk Limited
Registered in England and Wales

logo-devseccon