or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cleanup.mderror-snapshots.mdindex.mdpath-resolution.mdserialization.mdsnapshot-matchers.mdstate-management.md
tile.json

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/jest-snapshot@30.1.x

To install, run

npx @tessl/cli install tessl/npm-jest-snapshot@30.1.0

index.mddocs/

Jest Snapshot

Jest Snapshot provides comprehensive snapshot testing functionality for the Jest testing framework, enabling developers to capture and compare serialized representations of JavaScript objects, React components, API responses, and other testable outputs. It offers powerful snapshot matchers, sophisticated serialization, property-based partial matching, and robust snapshot lifecycle management with both external snapshot files and inline snapshots.

Package Information

  • Package Name: jest-snapshot
  • Package Type: npm
  • Language: TypeScript
  • Installation: Typically included with Jest. Can be installed directly with npm install jest-snapshot if needed.

Core Imports

import { 
  SnapshotState,
  addSerializer,
  getSerializers,
  buildSnapshotResolver,
  isSnapshotPath,
  cleanup,
  EXTENSION
} from "jest-snapshot";

For CommonJS:

const { 
  SnapshotState,
  addSerializer,
  getSerializers,
  buildSnapshotResolver,
  isSnapshotPath,
  cleanup,
  EXTENSION
} = require("jest-snapshot");

Note: The snapshot matchers (toMatchSnapshot, toMatchInlineSnapshot, etc.) are not direct exports from jest-snapshot. They are automatically added to Jest's expect() function when using Jest.

Basic Usage

import { SnapshotState, addSerializer } from "jest-snapshot";

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

// Inline snapshot matching
test('simple calculation', () => {
  const result = calculate(2, 3);
  expect(result).toMatchInlineSnapshot(`5`);
});

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

// Error snapshot testing
test('function throws expected error', () => {
  expect(() => {
    throwError();
  }).toThrowErrorMatchingSnapshot();
});

// Using SnapshotState directly (advanced usage)
const snapshotState = new SnapshotState('/path/to/snapshots', {
  updateSnapshot: 'none',
  snapshotFormat: {},
  rootDir: '/project/root'
});

// Adding custom serializers
addSerializer({
  test: (val) => val && val.constructor === MyClass,
  serialize: (val) => `MyClass { ${val.name} }`
});

Architecture

Jest Snapshot is built around several key architectural components:

  • Snapshot Matchers: Jest matchers (toMatchSnapshot, toMatchInlineSnapshot) implemented by this package and added to Jest's expect function
  • State Management: SnapshotState class manages snapshot file operations, counters, and test execution state
  • Path Resolution: Flexible snapshot file location system with customizable resolvers
  • Serialization Engine: Pluggable serialization system with built-in support for React components, DOM elements, and custom objects
  • Inline Processing: AST-based inline snapshot embedding and updating in source code
  • Property Matching: Partial object comparison with property matchers for dynamic values

Capabilities

Snapshot Matchers

Core snapshot testing functions for comparing values against stored snapshots. Supports both external .snap files and inline snapshots embedded in source code.

function toMatchSnapshot(hint?: string): MatcherResult;
function toMatchSnapshot<U extends Record<keyof T, unknown>>(
  propertyMatchers: Partial<U>, 
  hint?: string
): MatcherResult;

function toMatchInlineSnapshot(snapshot?: string): MatcherResult;
function toMatchInlineSnapshot<U extends Record<keyof T, unknown>>(
  propertyMatchers: Partial<U>, 
  snapshot?: string
): MatcherResult;

Snapshot Matchers

Error Snapshot Testing

Specialized matchers for testing error messages and exception handling with snapshot comparison.

function toThrowErrorMatchingSnapshot(hint?: string): MatcherResult;
function toThrowErrorMatchingInlineSnapshot(snapshot?: string): MatcherResult;

Error Snapshot Testing

State Management

The SnapshotState class handles snapshot file operations, maintains test execution state, and manages snapshot lifecycle.

class SnapshotState {
  constructor(snapshotPath: string, options: SnapshotStateOptions);
  
  // Public properties
  added: number;
  matched: number;
  unmatched: number;
  updated: number;
  expand: boolean;
  readonly snapshotFormat: SnapshotFormat;
  
  // Public methods
  match(options: SnapshotMatchOptions): SnapshotReturnOptions;
  fail(testName: string, received: unknown, key?: string): string;
  save(): SaveStatus;
  clear(): void;
  getUncheckedCount(): number;
  getUncheckedKeys(): Array<string>;
  removeUncheckedKeys(): void;
  markSnapshotsAsCheckedForTest(testName: string): void;
}

State Management

Path Resolution

Snapshot file path management system that resolves between test files and their corresponding snapshot files.

function buildSnapshotResolver(
  config: Config.ProjectConfig, 
  localRequire?: Promise<LocalRequire> | LocalRequire
): Promise<SnapshotResolver>;

function isSnapshotPath(path: string): boolean;

const EXTENSION: string; // 'snap'

interface SnapshotResolver {
  resolveSnapshotPath(testPath: string, snapshotExtension?: string): string;
  resolveTestPath(snapshotPath: string, snapshotExtension?: string): string;
  testPathForConsistencyCheck: string;
}

Path Resolution

Serialization and Plugins

Pluggable serialization system for customizing how values are converted to snapshot strings.

function addSerializer(plugin: PrettyFormatPlugin): void;
function getSerializers(): PrettyFormatPlugins;

// Plugin types from pretty-format
interface PrettyFormatPlugin {
  serialize(
    val: any,
    config: Config,
    indentation: string,
    depth: number,
    refs: Refs,
    printer: Printer
  ): string;
  test(val: any): boolean;
}

type PrettyFormatPlugins = PrettyFormatPlugin[];

Serialization and Plugins

Cleanup Operations

Utility functions for maintaining snapshot files and removing orphaned snapshots.

function cleanup(
  fileSystem: FileSystem,
  update: Config.SnapshotUpdateState,
  snapshotResolver: SnapshotResolver,
  testPathIgnorePatterns?: string[]
): {
  filesRemoved: number;
  filesRemovedList: Array<string>;
};

Cleanup Operations

Types

Core Interfaces

interface Context extends MatcherContext {
  snapshotState: SnapshotState;
  testFailing?: boolean;
}

interface SnapshotMatchers<R extends void | Promise<void>, T> {
  toMatchSnapshot(hint?: string): R;
  toMatchSnapshot<U extends Record<keyof T, unknown>>(
    propertyMatchers: Partial<U>,
    hint?: string
  ): R;
  toMatchInlineSnapshot(snapshot?: string): R;
  toMatchInlineSnapshot<U extends Record<keyof T, unknown>>(
    propertyMatchers: Partial<U>,
    snapshot?: string
  ): R;
  toThrowErrorMatchingSnapshot(hint?: string): R;
  toThrowErrorMatchingInlineSnapshot(snapshot?: string): R;
}

interface FileSystem {
  exists(path: string): boolean;
  matchFiles(pattern: RegExp | string): Array<string>;
}

type SnapshotFormat = Omit<PrettyFormatOptions, 'compareKeys'>;

interface InlineSnapshot {
  snapshot: string;
  frame: Frame;
  node?: Expression;
}

Configuration Types

interface SnapshotStateOptions {
  readonly updateSnapshot: Config.SnapshotUpdateState;
  readonly prettierPath?: string | null;
  readonly expand?: boolean;
  readonly snapshotFormat: SnapshotFormat;
  readonly rootDir: string;
}

interface SnapshotMatchOptions {
  readonly testName: string;
  readonly received: unknown;
  readonly key?: string;
  readonly inlineSnapshot?: string;
  readonly isInline: boolean;
  readonly error?: Error;
  readonly testFailing?: boolean;
}

interface SnapshotReturnOptions {
  readonly actual: string;
  readonly count: number;
  readonly expected?: string;
  readonly key: string;
  readonly pass: boolean;
}

interface SaveStatus {
  deleted: boolean;
  saved: boolean;
}

interface MatchSnapshotConfig {
  context: Context;
  hint?: string;
  inlineSnapshot?: string;
  isInline: boolean;
  matcherName: string;
  properties?: object;
  received: any;
}