Filters
Reference for all built-in filter classes.
Overview
Filters remove nodes from the value before it is serialized. They are applied in order
before any redactions. Multiple filters can be composed in the filters option array.
import { NullFilter, ExcludeFilter } from "vitest-snap";
const filters = [new NullFilter(), new ExcludeFilter(".internalId")];
// will filter out `null` values and exclude `internalId` prop from the received object
await expect(data).toJsonSnapshot({ filters });UndefinedFilter
Removes every property whose value is undefined, at any depth.
Applied by default. Pass a custom filters array to override.
Constructor
new UndefinedFilter();Example
import { UndefinedFilter } from "vitest-snap";
const filter = new UndefinedFilter();
filter.apply({ a: 1, b: undefined, c: { d: undefined, e: 2 } });
// → { a: 1, c: { e: 2 } }NullFilter
Removes every property whose value is null, at any depth.
Constructor
new NullFilter();Example
import { NullFilter } from "vitest-snap";
const filter = new NullFilter();
filter.apply({ a: 1, b: null, c: { d: null, e: 2 } });
// → { a: 1, c: { e: 2 } }Usage in snapshot
await expect(data).toJsonSnapshot({
filters: [new NullFilter()],
});ExcludeFilter
Removes all nodes matched by the given selector. All other nodes are kept.
Constructor
new ExcludeFilter(selector: Selector<T>)| Parameter | Type | Description |
|---|---|---|
selector | Selector<T> | Path expression targeting the nodes to remove |
Example
import { ExcludeFilter } from "vitest-snap";
const filter = new ExcludeFilter(".password");
filter.apply({ id: 1, name: "Alice", password: "secret" });
// → { id: 1, name: "Alice" }Nested path
new ExcludeFilter(".metadata.internalId");Wildcard — exclude a field from every array element
new ExcludeFilter(".users[].token");IncludeFilter
Keeps only the nodes matched by the given selectors. All other nodes are removed.
Multiple IncludeFilter instances (or bare Selector strings placed adjacent
to each other in the filters array) are automatically merged into one
filter.
Constructor
new IncludeFilter(selectors: Selector<T> | Selector<T>[])| Parameter | Type | Description |
|---|---|---|
selectors | Selector<T> or Selector<T>[] | Path expressions for nodes to keep |
Example — single selector
import { IncludeFilter } from "vitest-snap";
const filter = new IncludeFilter(".name");
filter.apply({ id: 1, name: "Alice", password: "secret" });
// → { name: "Alice" }Example — multiple selectors
new IncludeFilter([".id", ".name", ".email"]);Example — mixed array shorthand
Adjacent bare selectors in filters are merged automatically:
await expect(user).toJsonSnapshot({
filters: [".id", ".name", ".email"],
// equivalent to: [new IncludeFilter([".id", ".name", ".email"])]
});Adjacent bare Selector strings in the array are automatically merged into a
single IncludeFilter, so you can mix selectors and filter instances freely.
Last updated on