vitest-snap

toMarkdownSnapshot

Snapshot matcher that renders objects and arrays as Markdown tables.

Signature

toMarkdownSnapshot(options?: SnapMarkdownOptions<T>): Promise<void>

Description

Converts the received value to a Markdown table and writes it to a snapshot file. On subsequent runs the file content is diffed — the test fails if it differs.

Before rendering, the value passes through the same filters and redactions pipeline as toJsonSnapshot. The final Markdown is written via toMatchFileSnapshot.

Rendering rules

InputOutput
Array of objectsOne row per element; columns = union of all keys
Single objectOne row; columns = object keys
Primitive / non-objectSingle-column table with header value
null / undefined cellEmpty string
Nested object cellJSON.stringify(value)
Date cell.toISOString()

Defaults applied automatically

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

Options

type SnapMarkdownOptions<T> = {
  dir?: string;
  name?: string;
  fileExtension?: string;
  args?: any[];
  filters?: (Selector<T> | Filter<T>)[];
  redactions?: Redaction<T>[];
};
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 rendering — see Filters
redactions[new ValueRedaction(isDate, "[Date]")]Redactions applied after filters — see Redactions

Examples

Array of objects

test("user list", async () => {
  const users = [
    { id: 1, name: "Alice", role: "admin" },
    { id: 2, name: "Bob", role: "viewer" },
  ];
  await expect(users).toMarkdownSnapshot();
});

Snapshot file:

| id  | name  | role   |
| --- | ----- | ------ |
| 1   | Alice | admin  |
| 2   | Bob   | viewer |

Single object

test("config object", async () => {
  const config = { host: "localhost", port: 5432, ssl: true };
  await expect(config).toMarkdownSnapshot({ fileExtension: "md" });
});

Snapshot file:

| host      | port | ssl  |
| --------- | ---- | ---- |
| localhost | 5432 | true |

With custom file extension

test("report", async () => {
  await expect(rows).toMarkdownSnapshot({ fileExtension: "md" });
  // writes: ./snapshots/report.md
});

Parameterized snapshots

test.each(["admin", "viewer"])("users with role %s", async (role) => {
  const users = await fetchUsersByRole(role);
  await expect(users).toMarkdownSnapshot({ args: [role] });
  // writes: ./snapshots/users-with-role-admin
  // writes: ./snapshots/users-with-role-viewer
});

Exclude sensitive columns

import { ExcludeFilter } from "vitest-snap";

test("public user list", async () => {
  await expect(users).toMarkdownSnapshot({
    filters: [new ExcludeFilter(".passwordHash")],
  });
});

Last updated on

On this page