6 stages of refactoring a Jest test case

Écrit par:
wordpress-sync/Screen-Shot-2019-09-04-at-10.20.00

4 septembre 2019

0 minutes de lecture

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.

Publié dans:Ingénierie

Snyk est une plateforme de sécurité des développeurs. S’intégrant directement aux outils, workflows et pipelines de développement, Snyk facilite la détection, la priorisation et la correction des failles de sécurité dans le code, les dépendances, les conteneurs et l’infrastructure en tant que code (IaC). Soutenu par une intelligence applicative et sécuritaire de pointe, Snyk intègre l'expertise de la sécurité au sein des outils de chaque développeur.

Démarrez gratuitementRéservez une démo en ligne

© 2024 Snyk Limited
Enregistré en Angleterre et au Pays de Galles

logo-devseccon