Jest Snapshot Diffing Utility

0.10.0 · active · verified Tue Apr 21

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.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates using `toMatchDiffSnapshot` for comparing React component states, strings, and plain objects, along with configuring the recommended snapshot serializer.

import React from 'react';
import { toMatchDiffSnapshot, getSnapshotDiffSerializer } from 'snapshot-diff';

// Extend Jest's expect with the custom matcher
expect.extend({ toMatchDiffSnapshot });

// Add the custom serializer to prevent extra quotes in snapshots
expect.addSnapshotSerializer(getSnapshotDiffSerializer());

// Define a simple React component for demonstration
interface ComponentProps {
  value: string;
}

const MyComponent: React.FC<ComponentProps> = ({ value }) => {
  return (
    <div>
      <p>Current value: {value}</p>
      <button onClick={() => console.log('clicked')}>Click Me</button>
    </div>
  );
};

describe('snapshot-diff usage', () => {
  test('should diff changes in React component props', () => {
    const initialElement = <MyComponent value="initial" />;
    const updatedElement = <MyComponent value="changed" />;

    // Compare the two React elements directly with the custom matcher
    expect(initialElement).toMatchDiffSnapshot(updatedElement);
  });

  test('should diff differences between two strings', () => {
    const stringA = 'The quick brown fox jumps over the lazy dog.';
    const stringB = 'The quick red fox jumps over the sleeping cat.';

    // Compare two strings directly
    expect(stringA).toMatchDiffSnapshot(stringB);
  });

  test('should diff two plain objects', () => {
    const objA = { id: 1, name: 'Alice', age: 30 };
    const objB = { id: 1, name: 'Alicia', age: 31, city: 'NY' };

    // Compare two plain objects
    expect(objA).toMatchDiffSnapshot(objB);
  });
});

view raw JSON →