vitest-snap

toYamlSnapshot

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

Signature

toYamlSnapshot(options?: SnapYamlOptions<T>): Promise<void>

Description

Serializes the received value to a YAML 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 yaml.stringify(value, { 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 SnapYamlOptions<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 for YAML indentation

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).toYamlSnapshot();
  // writes: ./snapshots/user-object
  // id: 1
  // name: Alice
  // createdAt: "[Date_1]"
});

Custom file extension

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

Parameterized snapshots

test.each([10, 50, 100])("pagination page-size %i", async (pageSize) => {
  const result = await fetchUsers({ pageSize });
  await expect(result).toYamlSnapshot({ 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).toYamlSnapshot({
    filters: [new NullFilter(), new ExcludeFilter(".internalId")],
  });
});

Custom redactions

import { ReplacedRedaction } from "vitest-snap";

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

Include only specific fields

import { IncludeFilter } from "vitest-snap";

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

Last updated on

On this page