vitest-snap

toJsonSnapshot

Snapshot matcher for JSON-serializable values with filtering and redaction support.

Signature

toJsonSnapshot(options?: SnapJsonOptions<T>): Promise<void>

Description

Serializes the received value to a formatted JSON string and writes it to a snapshot file. On subsequent runs the file content is diffed — the test fails if it differs.

Before serialization, the value is passed through the configured filters and redactions pipeline:

  1. Clone input value.
  2. Apply each filter in order.
  3. Apply each redaction in order.
  4. Serialize with JSON.stringify(value, null, indent).
  5. Write to snapshot file via toMatchFileSnapshot.

Defaults applied automatically

ConcernDefault behaviour
undefined propsRemoved by UndefinedFilter
Date valuesReplaced with [Date_1], [Date_2], … by ValueRedaction

Options

type SnapJsonOptions<T> = {
  dir?: string;
  name?: string;
  fileExtension?: string;
  args?: any[];
  filters?: (Selector<T> | Filter<T>)[];
  redactions?: Redaction<T>[];
  indent?: number;
};
OptionDefaultDescription
dir"./snapshots"Directory relative to the test file
namecurrent test nameSlug used as the base filename
fileExtensionnoneExtension appended to the file
args[]Extra segments for parametric snapshots
filters[new UndefinedFilter()]Filters applied before serialization — see Filters
redactions[new ValueRedaction(isDate, "[Date]")]Redactions applied after filters — see Redactions
indent2Spaces used by JSON.stringify

Examples

Basic usage

import { describe, expect, test } from "vitest";

test("user object", async () => {
  const user = { id: 1, name: "Alice", createdAt: new Date() };
  await expect(user).toJsonSnapshot();
  // writes: ./snapshots/user-object
  // { "id": 1, "name": "Alice", "createdAt": "[Date_1]" }
});

Custom file extension

test("config", async () => {
  await expect(config).toJsonSnapshot({ fileExtension: "json" });
  // writes: ./snapshots/config.json
});

Parameterized snapshots

test.each([10, 50, 100])("pagination page-size %i", async (pageSize) => {
  const result = await fetchUsers({ pageSize });
  await expect(result).toJsonSnapshot({ args: [pageSize] });
  // writes: ./snapshots/pagination-page-size-10
  // writes: ./snapshots/pagination-page-size-50
  // writes: ./snapshots/pagination-page-size-100
});

Custom filters

import { NullFilter, ExcludeFilter } from "vitest-snap";

test("filtered snapshot", async () => {
  await expect(data).toJsonSnapshot({
    filters: [new NullFilter(), new ExcludeFilter(".internalId")],
  });
});

Custom redactions

import { ReplacedRedaction } from "vitest-snap";

test("redacted snapshot", async () => {
  await expect(user).toJsonSnapshot({
    redactions: [new ReplacedRedaction(".password", "[REDACTED]")],
  });
});

Include only specific fields

import { IncludeFilter } from "vitest-snap";

test("public fields only", async () => {
  await expect(user).toJsonSnapshot({
    filters: [".id", ".name", ".email"],
  });
});

Last updated on

On this page