Jest snapshot testing utilities that enable capturing component output, API responses, or any serializable values as snapshots for regression testing and change detection
npx @tessl/cli install tessl/npm-jest-snapshot@30.1.0Jest 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.
npm install jest-snapshot if needed.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.
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} }`
});Jest Snapshot is built around several key architectural components:
toMatchSnapshot, toMatchInlineSnapshot) implemented by this package and added to Jest's expect functionSnapshotState class manages snapshot file operations, counters, and test execution stateCore 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;Specialized matchers for testing error messages and exception handling with snapshot comparison.
function toThrowErrorMatchingSnapshot(hint?: string): MatcherResult;
function toThrowErrorMatchingInlineSnapshot(snapshot?: string): MatcherResult;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;
}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;
}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[];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>;
};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;
}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;
}