jest/prefer-snapshot-hint

Require a hint on toMatchSnapshot() and toThrowErrorMatchingSnapshot()

Snapshots in a .snap file are named after the test and numbered: renders the menu 1, renders the menu 2. With several in one test, you can't tell which snapshot belongs to which expect, and adding one in the middle renumbers the rest. A hint becomes part of the name: renders the menu: closed 1.

By default a hint is only required in a test that has more than one snapshot. Inline snapshots aren't checked.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"jest/prefer-snapshot-hint" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"jest/prefer-snapshot-hint" = ["error", "multi"] # "multi" or "always"

Examples#

example.ts2 problems
import { expect, test } from "@jest/globals";

test("renders the menu", () => {
  expect(renderMenu({ open: false })).toMatchSnapshot();
  expect(renderMenu({ open: true })).toMatchSnapshot();
});
example.tsNo problems
import { expect, test } from "@jest/globals";

test("renders the menu", () => {
  expect(renderMenu({ open: false })).toMatchSnapshot("closed");
  expect(renderMenu({ open: true })).toMatchSnapshot("open");
});

test("renders the footer", () => {
  expect(renderFooter()).toMatchSnapshot();
});

A single argument only counts as a hint if it's a string or a template literal. Property matchers or a variable are reported:

example.ts2 problems
import { expect, test } from "@jest/globals";

test("creates users", () => {
  expect(createUser("Ada")).toMatchSnapshot({ id: expect.any(Number) });
  expect(createUser("Grace")).toMatchSnapshot(hint);
});

With property matchers, the hint is the second argument:

example.tsNo problems
import { expect, test } from "@jest/globals";

test("creates users", () => {
  expect(createUser("Ada")).toMatchSnapshot({ id: expect.any(Number) }, "first user");
  expect(createUser("Grace")).toMatchSnapshot({ id: expect.any(Number) }, "second user");
});

Options#

bunfig.toml
[lint.rules]
"jest/prefer-snapshot-hint" = ["error", "always"]
OptionWhat it does
"multi" (default)Require a hint if the test has more than one snapshot.
"always"Require a hint on every snapshot.
example.tswith "always"1 problem
import { expect, test } from "@jest/globals";

test("renders the footer", () => {
  expect(renderFooter()).toMatchSnapshot();
});