Home / Companies / Mergify / Blog / Post Details
Content Deep Dive

Jest snapshot drift: when toMatchSnapshot lies about your code

Blog post from Mergify

Post Details
Company
Date Published
Author
-
Word Count
1,090
Language
English
Hacker News Points
-
Summary

Rémy Duthu's article addresses the issue of snapshot drift in Jest testing, where snapshots fail due to changes that developers did not cause, often leading teams to mistakenly blame Date.now() mocks. The real culprits are three less-obvious sources of drift: generated identifiers, Map and Set iteration order, and global counters. These result in non-deterministic snapshots due to factors like fresh UUIDs, non-guaranteed ordering from upstream APIs, and global counter increments. A solution involves using custom serializers in Jest to replace unstable values with stable placeholders, thus maintaining structural assertions without noise. Additionally, the article suggests using property matchers for intrinsically variable values and highlights tools like Mergify to make snapshot drift more legible by grouping failures and identifying drift patterns. The piece urges a shift away from using snapshots for certain variable data and suggests best practices for preventing shared state issues across tests.