Snapshot Serializers in Jest
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.
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.