snapshot-diff is a utility library for Jest that facilitates the creation of diff snapshots between two values, particularly useful for comparing states of React components. The current stable version is 0.10.0. The library's release cadence is tightly coupled with Jest's major releases, leading to frequent breaking changes primarily due to updates in its Jest peer dependencies. It offers both a direct `snapshotDiff` function and a custom Jest matcher, `toMatchDiffSnapshot`, to integrate seamlessly into Jest tests. A key differentiator is its ability to provide readable, Git-style diff output for complex data structures by leveraging Jest's serialization mechanisms and supporting custom serializers.
npm install snapshot-diffVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates using `toMatchDiffSnapshot` for comparing React component states, strings, and plain objects, along with configuring the recommended snapshot serializer.
Ensure your `jest` version meets the peer dependency requirements of `snapshot-diff`. Update `jest` if necessary, or downgrade `snapshot-diff` to a compatible version. Refer to the `peerDependencies` in `package.json`.
Update your `@types/jest` package to match your Jest version and the `snapshot-diff` requirements. Review any TypeScript errors related to `jest.Matchers` or `SnapshotSerializer` interfaces in your project.
Add `expect.addSnapshotSerializer(getSnapshotDiffSerializer());` in your Jest setup file (e.g., `setupFilesAfterEnv`) to ensure diffs are clean and human-readable.
When calling `snapshotDiff.setSerializers(mySerializers)`, ensure `...defaultSerializers` (imported from `snapshot-diff`) is spread into your custom array if you still need default React component serialization.
Ensure you either `import { toMatchDiffSnapshot } from 'snapshot-diff'; expect.extend({ toMatchDiffSnapshot });` or `import 'snapshot-diff/extend-expect';` in your Jest setup file or relevant test files.Ensure `react-test-renderer` is correctly installed as a development dependency. If using Yarn or PNPM, check for hoisted dependencies or use `resolutions` to enforce a single version. Clearing `node_modules` and `package-lock.json`/`yarn.lock` and reinstalling often resolves this.
Ensure `snapshot-diff` is installed and that `@types/jest` (if Jest is a peer dependency) is also installed. Verify your `tsconfig.json` includes `node_modules/@types` in `typeRoots` and `types` arrays are correctly configured, or that it is implicitly picked up.
Review your custom serializer implementation. It must export an object with at least `test` and `print` methods, and optionally `serialize` and `deserialize`.