CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jest-image-snapshot

Jest matcher for image comparisons used for visual regression testing.

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

core-matcher.mddocs/

Core Matcher

The toMatchImageSnapshot matcher is the primary function that performs image comparison against stored snapshots, integrating seamlessly with Jest's snapshot testing workflow.

Capabilities

toMatchImageSnapshot Matcher

Performs image comparison by creating baseline snapshots on first run and comparing subsequent images against these baselines.

/**
 * Jest matcher that compares an image buffer against a stored snapshot
 * @param received - Image buffer (Buffer, string, or Uint8Array)
 * @param options - Configuration options for comparison
 */
function toMatchImageSnapshot(options?: MatcherOptions): void;

interface MatcherOptions {
  /** Custom configuration for pixelmatch or SSIM comparison algorithms */
  customDiffConfig?: CustomDiffConfig;
  /** Comparison method: 'pixelmatch' (default) or 'ssim' */
  comparisonMethod?: 'pixelmatch' | 'ssim';
  /** Custom identifier for snapshot file naming */
  customSnapshotIdentifier?: string | CustomSnapshotIdentifierFunction;
  /** Custom directory path for storing snapshots */
  customSnapshotsDir?: string;
  /** Custom directory path for storing diff images */
  customDiffDir?: string;
  /** Custom directory path for storing received images on failure */
  customReceivedDir?: string;
  /** Custom postfix for received image filenames (default: '-received') */
  customReceivedPostfix?: string;
  /** Store received images separately on test failure (default: false) */
  storeReceivedOnFailure?: boolean;
  /** Layout direction for diff images: 'horizontal' (default) or 'vertical' */
  diffDirection?: 'horizontal' | 'vertical';
  /** Only show diff in output image, exclude baseline and received (default: false) */
  onlyDiff?: boolean;
  /** Remove colors from console output (default: false) */
  noColors?: boolean;
  /** Threshold for test failure based on failureThresholdType (default: 0) */
  failureThreshold?: number;
  /** Type of threshold: 'pixel' (default) or 'percent' */
  failureThresholdType?: 'pixel' | 'percent';
  /** Update snapshots even when tests pass (default: false) */
  updatePassedSnapshot?: boolean;
  /** Gaussian blur radius in pixels for noise reduction (default: 0) */
  blur?: number;
  /** Run comparison in same process instead of child process (default: false) */
  runInProcess?: boolean;
  /** Output base64 diff string to console on failure (default: false) */
  dumpDiffToConsole?: boolean;
  /** Output inline diff to terminal using iTerm protocol (default: false) */
  dumpInlineDiffToConsole?: boolean;
  /** Allow images with different dimensions (default: false) */
  allowSizeMismatch?: boolean;
  /** Maximum buffer size for child process in bytes (default: 10MB) */
  maxChildProcessBufferSizeInBytes?: number;
  /** Path to runtime hooks file for custom image processing */
  runtimeHooksPath?: string;
}

Usage Examples:

// Basic usage
expect(imageBuffer).toMatchImageSnapshot();

// With threshold configuration
expect(imageBuffer).toMatchImageSnapshot({
  failureThreshold: 0.01,
  failureThresholdType: 'percent'
});

// With custom snapshot identifier
expect(imageBuffer).toMatchImageSnapshot({
  customSnapshotIdentifier: 'header-component-desktop'
});

// With custom diff configuration
expect(imageBuffer).toMatchImageSnapshot({
  customDiffConfig: { threshold: 0.1 },
  comparisonMethod: 'pixelmatch'
});

// SSIM comparison method
expect(imageBuffer).toMatchImageSnapshot({
  comparisonMethod: 'ssim',
  customDiffConfig: { ssim: 'fast' },
  failureThreshold: 0.01,
  failureThresholdType: 'percent'
});

// Custom directories and options
expect(imageBuffer).toMatchImageSnapshot({
  customSnapshotsDir: path.join(__dirname, 'snapshots'),
  customDiffDir: path.join(__dirname, 'diffs'),
  storeReceivedOnFailure: true,
  diffDirection: 'vertical'
});

Image Input Handling

The matcher accepts various image input formats and converts them to PNG buffers for comparison.

/**
 * Supported image input types:
 * - Buffer: PNG image data
 * - string: Base64 encoded image data
 * - Uint8Array: Raw image bytes
 */
type ImageInput = Buffer | string | Uint8Array;

Custom Snapshot Identifier Function

Function interface for generating custom snapshot identifiers, especially useful with jest.retryTimes().

interface CustomSnapshotIdentifierFunction {
  (params: {
    testPath: string;
    currentTestName: string;
    counter: number;
    defaultIdentifier: string;
  }): string;
}

Usage Example:

expect(imageBuffer).toMatchImageSnapshot({
  customSnapshotIdentifier: ({ testPath, currentTestName, counter }) => {
    return `${path.basename(testPath)}-${currentTestName}-${counter}-custom`;
  }
});

Jest Integration

The matcher integrates with Jest's snapshot system and supports all Jest snapshot features:

  • Snapshot Updates: Use jest --updateSnapshot or -u to update snapshots
  • CI Mode: Prevents new snapshot creation in CI environments
  • Retry Support: Compatible with jest.retryTimes() when using custom identifiers
  • Test Context: Accesses Jest's test context including file paths and test names

Jest Retry Example:

// Required when using jest.retryTimes()
jest.retryTimes(2);

it('flaky visual test', () => {
  expect(imageBuffer).toMatchImageSnapshot({
    customSnapshotIdentifier: 'unique-identifier-for-retry'
  });
});

Error Handling

The matcher provides detailed error messages and handles various failure scenarios:

  • Size Mismatches: Clear reporting when image dimensions differ
  • Threshold Failures: Percentage and pixel count reporting
  • File System Errors: Proper error handling for directory creation and file operations
  • Invalid Options: Validation of configuration parameters

Common Error Scenarios:

// Size mismatch error
expect(imageBuffer).toMatchImageSnapshot({
  allowSizeMismatch: false // Will fail if dimensions differ
});

// Threshold exceeded error
expect(imageBuffer).toMatchImageSnapshot({
  failureThreshold: 0.001,
  failureThresholdType: 'percent' // Will fail if > 0.1% different
});

// Invalid usage
expect(imageBuffer).not.toMatchImageSnapshot(); // Throws error - .not not supported

docs

configuration.md

core-matcher.md

index.md

snapshot-management.md

tile.json