Snapshot Serializers in Jest

David Barral
Trabe
Published in
2 min readMar 26, 2018
Photo by freestocks.org from Pexels

If you have been snapshot testing your React components with Jest and Enzyme, your Jest configuration probably contains this:

Maybe you haven’t thought about its meaning too much: it’s just some config line you need. However, this line is the key to have programmer friendly snapshots. Consider the following example:

By using the enzyme-to-json custom serializer you go from a complex (almost useless) output to something human readable in diff format.

Default serialization vs custom (enzyme-to-json)

Make your own serializer

Adding custom serializers to your test suite is easy. You can either define them in place using expect.addSnapshotSerializer or set them in the config file (snapshotSerializers config key).

A serializer is an object with two methods test and print. When Jest serializes a value it will try to match against the test function. If it matches, it will serialize the value using print.

print also receives a serialization function to allow recursive serialization, and an indentation function.

Meaningful diffs with custom serializers

Serializers can be a very powerful tool. By customizing the snapshot output you can focus on the details that matters to your test. It removes all the unnecessary noise and ease the scanning of diffs to see what changes in each test run. Give it a try. You won’t regret it.

--

--

David Barral
Trabe
Editor for

Co-founder @Trabe. Developer drowning in a sea of pointless code.