CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jest-snapshot

Jest snapshot testing utilities that enable capturing component output, API responses, or any serializable values as snapshots for regression testing and change detection

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

snapshot-matchers.mddocs/

Snapshot Matchers

Jest matchers that compare received values against stored snapshots, supporting both external .snap files and inline snapshots embedded directly in source code. These matchers are implemented by jest-snapshot and automatically added to Jest's expect() function.

Capabilities

toMatchSnapshot

Compares a received value against a stored snapshot in an external .snap file. Supports optional property matchers for partial object comparison and hint strings for multiple snapshots in a single test.

/**
 * Ensures that a value matches the most recent snapshot
 * @param hint - Optional hint string to distinguish multiple snapshots in one test
 * @returns Matcher result indicating pass/fail status
 */
function toMatchSnapshot(hint?: string): MatcherResult;

/**
 * Ensures that a value matches the most recent snapshot with property matchers
 * @param propertyMatchers - Partial object with expected property values or matchers
 * @param hint - Optional hint string to distinguish multiple snapshots in one test
 * @returns Matcher result indicating pass/fail status
 */
function toMatchSnapshot<U extends Record<keyof T, unknown>>(
  propertyMatchers: Partial<U>, 
  hint?: string
): MatcherResult;

Usage Examples:

// Note: toMatchSnapshot is automatically available on expect() when using Jest
// No import from jest-snapshot is needed

// Basic snapshot matching
test('renders component correctly', () => {
  const component = render(<MyComponent />);
  expect(component).toMatchSnapshot();
});

// Multiple snapshots with hints
test('renders in different states', () => {
  expect(render(<Button disabled />)).toMatchSnapshot('disabled state');
  expect(render(<Button loading />)).toMatchSnapshot('loading state');
});

// Property matching for dynamic values
test('user with partial matching', () => {
  const user = { 
    id: 123, 
    name: 'John', 
    timestamp: Date.now(),
    settings: { theme: 'dark' }
  };
  
  expect(user).toMatchSnapshot({
    id: expect.any(Number),
    name: 'John',
    settings: { theme: 'dark' }
    // timestamp excluded from snapshot
  });
});

toMatchInlineSnapshot

Compares a received value against an inline snapshot that is written directly into the source code. The snapshot value is embedded as a string argument to the matcher function.

/**
 * Ensures that a value matches an inline snapshot in source code
 * @param snapshot - Optional existing snapshot string (auto-generated if omitted)
 * @returns Matcher result indicating pass/fail status
 */
function toMatchInlineSnapshot(snapshot?: string): MatcherResult;

/**
 * Ensures that a value matches an inline snapshot with property matchers
 * @param propertyMatchers - Partial object with expected property values or matchers
 * @param snapshot - Optional existing snapshot string (auto-generated if omitted)
 * @returns Matcher result indicating pass/fail status
 */
function toMatchInlineSnapshot<U extends Record<keyof T, unknown>>(
  propertyMatchers: Partial<U>, 
  snapshot?: string
): MatcherResult;

Usage Examples:

// Note: toMatchInlineSnapshot is automatically available on expect() when using Jest
// No import from jest-snapshot is needed

// Basic inline snapshot (Jest will auto-generate the snapshot string)
test('calculates result', () => {
  const result = calculate(2, 3);
  expect(result).toMatchInlineSnapshot(`5`);
});

// Object inline snapshot
test('creates user object', () => {
  const user = createUser('John', 25);
  expect(user).toMatchInlineSnapshot(`
    Object {
      "age": 25,
      "id": Any<Number>,
      "name": "John",
    }
  `);
});

// Property matching with inline snapshot
test('API response with dynamic fields', () => {
  const response = await fetchUser(123);
  expect(response).toMatchInlineSnapshot(
    {
      timestamp: expect.any(Number),
      requestId: expect.any(String)
    },
    `
    Object {
      "data": Object {
        "name": "John",
        "email": "john@example.com"
      },
      "requestId": Any<String>,
      "status": "success",
      "timestamp": Any<Number>
    }
    `
  );
});

// Multi-line string snapshot
test('generates SQL query', () => {
  const query = buildQuery({ table: 'users', where: { active: true } });
  expect(query).toMatchInlineSnapshot(`
    "SELECT * FROM users 
     WHERE active = true"
  `);
});

Matcher Behavior

First Run: When a test runs for the first time:

  • toMatchSnapshot: Creates a new .snap file with the serialized value
  • toMatchInlineSnapshot: Inserts the serialized value directly into the source code

Subsequent Runs: On later test runs:

  • Compares the received value against the stored snapshot
  • Fails if values don't match (unless in update mode)

Update Mode: When running with --updateSnapshot:

  • Updates existing snapshots with new received values
  • Useful when intentional changes are made to components or data structures

Property Matchers: Allow partial snapshot matching:

  • Use expect.any(Type) for type-only matching
  • Use specific values for exact matches
  • Omit properties to exclude them from the snapshot entirely

Error Handling

Common error scenarios and their meanings:

// Missing snapshot state
expect(value).toMatchSnapshot(); 
// Error: "Snapshot state must be initialized"

// Invalid property matchers
expect(value).toMatchSnapshot(123); 
// Error: "Expected properties must be an object"

// Wrong property matcher type
expect(value).toMatchSnapshot({ id: 123 }, 456); 
// Error: "Inline snapshot must be a string"

// Using with .not modifier
expect(value).not.toMatchSnapshot(); 
// Error: "Snapshot matchers cannot be used with not"

Types

interface MatcherResult {
  message(): string;
  pass: boolean;
  actual?: unknown;
  expected?: unknown;
  name?: string;
}

type MatcherContext = {
  isNot: boolean;
  promise: string;
  currentTestName?: string;
  currentConcurrentTestName?: () => string;
  equals: (a: unknown, b: unknown, customTesters?: Array<Tester>) => boolean;
  utils: MatcherUtils;
  error?: Error;
  dontThrow?: () => void;
};

docs

cleanup.md

error-snapshots.md

index.md

path-resolution.md

serialization.md

snapshot-matchers.md

state-management.md

tile.json