Jest Snapshot testing

Today, we will talk about a useful tool called Jest Snapshot. This feature is the best option to make sure that our UI component does not change for no reason. We can also use Jest Snapshots as an ally to have unit tests that are cleaner and more maintainable, something that any developer will love.

Jest Snapshot: Testing a React web app using Jest and Enzyme

What is a Jest Snapshot?

A Jest Snapshot is a screenshot of the React tree from a specific moment of some UI component. Jest can use that screenshot to compare it with the actual React tree render, and if both instances don’t match, the test will fail. If the test fails, we’ll know that a change was introduced since the last snapshot. The change can be expected or unexpected; in the first case, we just need to update the snapshot to be aligned with the new version of the UI component, and in the second case, we should review the component to check why there are differences between both instances.

When can Jest Snapshots be useful?

Jest Snapshots can be used not only for components -though, components are the most common use for it-, we can also use them for serializable data, functions, or anytime we need to test whether the output is correct.

Let’s take a look at some examples. Imagine we have a Header component which renders a title and subtitle from data prop -check the code below- and we need to test the component. Forget about the prop for a minute and focus only on the render; we need to check if it renders a <div> with their class name and their children, another two <div> which have <h1> and <h3> with the current text. You are probably thinking about many ways to do these simple tests, but let’s take a look at how easy it can be using Jest Snapshots.

If we decide to use Jest Snapshots, we’ll just need to add one test! We have to check if the render matches the snapshot and that’s it. But we have even more good news! If the component changes some tag or text in the future, we only have to update the snapshot and the unit tests will succeed again.

Now let’s say we have a Constants file and we should generate their unit tests. As you can guess, the best way to do this is using Jest Snapshots.

If you still have doubts, we hope this example shows you how Jest Snapshots make your life easier regarding unit tests, as it makes no sense to do complex things when we only need to know if some constant value has been changed or not.

Conclusion

Jest Snapshot testing is a fantastic tool that allows you to test your UI component render in a quick and easy way, saving time to spend on tests that really need more attention. Also, we have the benefit of getting a more maintainable unit test code.

If you are interested in this topic or you want to learn more about Jest and Enzyme, you can read Mock Function: Testing a React web app using Jest and Enzyme and Async code: Testing a React web app using Jest and Enzyme