Why use snapshot testing with Jest

September 13, 2022 3 min read

Have you ever tried using snapshot testing in your React project, but always ended up finding it very dull and useless? Me too.

My main concern with snapshot testing was, how hard it is to identify the actual issue when a test is breaking, and always ending up updating meaningless classNames that have changed for some reason, when I modified some different parts of the code.

But then one day I realised that it doesn't have to be this way and snapshot testing can be in fact very useful with Jest.

The component to test

Lets say we have a small component which holds very little logic. It is rendering different statuses based on a prop called currStatus.

basic component

As you see if the currStatus equals loading a simple paragraph is being rendered with the text “loading” in it, and the same logic goes for success and error.

Testing the original way

You would normally test this component by adding a data-testid to each paragraph tag and then test each possibility and expect it to be present.

testing with targeting

This would be a good solution, but it requires some extra code and in case it breaks, you would have to console log things to see how has your html actually changed.

Snapshots to the rescue!

However, if you write the same with snapshot testing it becomes way more clear:

testing with snapshots

As you can see, jest takes care of matching the snapshot for you and you spare at least 1 line of code for each test. (that is a lot of lines when you have lots of tests)
In case something changed and the test breaks you can easily identify what has happened:

failed snapshot test It seems like the prop has changed and now an unknown status is being passed down so the default scenario is being rendered (null).

The takeaway

This might not seem as a very big improvement, but when you are trying to write tests for all your components it can save you a lot of time.
So next time an inexperienced startup founder or CTO needs some convincing why you are using snapshot tests, now you know how to prove them wrong!😊

Read Next

Increasing the test coverage of your React project

Testing is an important and essential part of software engineering, but when working on real life projects it can get hard sometimes to cover everything properly.

October 4, 2022 3 min read

Developer productivity hacks #1 - Testing your code very fast

Adding code to existing codebases can sometimes take a lot of time. What if I told you there are ways to reduce it?

October 18, 2022 4 min read