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:
- Clone input value.
- Apply each filter in order.
- Apply each redaction in order.
- Serialize with
yaml.stringify(value, { indent }). - Write to snapshot file via
toMatchFileSnapshot.
Defaults applied automatically
| Concern | Default behaviour |
|---|---|
undefined props | Removed by UndefinedFilter |
Date values | Replaced 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;
};| Option | Default | Description |
|---|---|---|
dir | "./snapshots" | Directory relative to the test file |
name | current test name | Slug used as the base filename |
fileExtension | none | Extension 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 |
indent | 2 | Spaces 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