skip to content

Snapshot Testing

toMatchSnapshot and inline snapshots, the update workflow, serializers, and being honest about when a snapshot is a real assertion versus a rubber stamp. Interviewers ask because blanket snapshot updates are a well-known team smell.

on this pageshow

explore

questions

6

In Jest 30, where does toMatchSnapshot store a snapshot, and how is each entry in that file named and matched?

level: juniorimportance: must knowfreq 58%

answer

  1. a folder beside the test file
  2. one .snap file per test file
  3. describe and test names joined
  4. a counter that restarts in each test

basics

~20 s

toMatchSnapshot serializes the value and stores it in snapshots/<test file>.snap beside the test, keyed by the full test name plus a counter; every later run serializes again and compares against the entry under that same key.

solid answer

~40 s

The first time `expect(value).toMatchSnapshot()` runs, Jest serializes the value with `pretty-format` and writes it to a `__snapshots__` folder next to the test, in a file named after the test file plus `.snap`: `format.test.js` gets `__snapshots__/format.test.js.snap`. Each entry is an `exports[...]` line keyed by the describe and test names joined with spaces plus a counter for that test, so two calls in one test become `renderConfig defaults 1` and `renderConfig defaults 2`. A `hint` argument is appended after a colon, as in `renderConfig defaults: retries 1`. Later runs re-serialize the value and compare the text with the entry under the same key, so renaming a test does not carry its entry along: the old one turns obsolete and, outside CI mode, a new one is written. The file is committed and reviewed like code.

code

javascript · 16 lines
javascript
const renderConfig = ({name, retries = 3}) => ({retries, name});
const parsePort = value => {
  const port = Number(value);
  if (!Number.isInteger(port)) throw new TypeError(`Invalid port: ${value}`);
  return port;
};

describe('renderConfig', () => {
  test('defaults', () => {
    expect(renderConfig({name: 'api'})).toMatchSnapshot();
  });
});

test('rejects a bad port', () => {
  expect(() => parsePort('eighty')).toThrowErrorMatchingSnapshot();
});

go deeper

for a junior

Recall the snapshots folder beside the test, one .snap file per test file, and that the file is committed and reviewed with the code.

for a middle

Explain how the key is built from the describe and test names, the hint and the counter, and why a rename leaves an obsolete entry behind.

for a senior

Show you can diagnose snapshot failures that come from keys rather than output: swapped calls, conditional calls, renamed blocks and orphaned files.

for a principal

Treat the snapshot file as a reviewed artifact: keys and value size decide whether reviewers can actually read what changed.

## What the matcher does `expect(value).toMatchSnapshot()` is a Jest matcher that turns a value into text and compares that text with a stored copy. There is no hand-written expected value: the stored copy *is* the expectation. The first run has nothing to compare against, so, outside CI mode, Jest records the text; every later run produces the text again and fails when it differs from what was recorded. The serializer is `pretty-format`, the same printer Jest uses for failure diffs. It handles objects, arrays, `Map`, `Set`, `Date`, errors, functions and DOM nodes, and any custom serializer you register goes in front of it. Two matchers write to the external file: `toMatchSnapshot(propertyMatchers?, hint?)` for any value, and `toThrowErrorMatchingSnapshot(hint?)`, which calls a function, catches what it throws and records the error message. Their inline twins, `toMatchInlineSnapshot` and `toThrowErrorMatchingInlineSnapshot`, store the text in the test source instead and never touch a `.snap` file. Everything below is about the file-based pair. ## Where the file lives - By default Jest writes to a `__snapshots__` folder **in the same directory as the test file**. - There is **one snapshot file per test file** that calls a file-based snapshot matcher, named after the test file plus `.snap`: `src/__tests__/format.test.js` gets `src/__tests__/__snapshots__/format.test.js.snap`. - The file opens with a header line, `// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing`, followed by one `exports[...]` assignment per snapshot. - The `snapshotResolver` config key points at a module with `resolveSnapshotPath` and `resolveTestPath` when a project wants the files somewhere else. ## How each entry is keyed The key is what ties a call in the test to an entry in the file, so knowing how it is built explains most surprises. | Call inside the test | Stored under | |---|---| | first `toMatchSnapshot()` in `test('defaults')` inside `describe('renderConfig')` | `renderConfig defaults 1` | | second `toMatchSnapshot()` in the same test | `renderConfig defaults 2` | | `toMatchSnapshot('retries')` (a hint) | `renderConfig defaults: retries 1` | | `toThrowErrorMatchingSnapshot()` in `test('rejects a bad port')` | `rejects a bad port 1` | 1. Jest takes the full test name: every enclosing `describe` name and the test name, joined with spaces. 2. It appends `: hint` when a hint string was passed. 3. It appends a counter for that name, starting at 1 in each test and rising with every further call under the same name. Jest also sorts the entries by key inside the file, so their order on disk says nothing about the order the calls ran in. ## What the stored text looks like - Objects print with their keys **sorted**, so the order fields were assigned in does not matter: an object built as `{retries, name}` is stored with `name` first. - Strings print in double quotes, and with the `snapshotFormat` default `{escapeString: false, printBasicPrototype: false}` they are not escaped and plain objects and arrays carry no `Object` or `Array` prefix. - An error thrown into `toThrowErrorMatchingSnapshot` is stored as its message string, not as the whole error object. ```plaintext // Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing exports[`rejects a bad port 1`] = `"Invalid port: eighty"`; exports[`renderConfig defaults 1`] = ` { "name": "api", "retries": 3, } `; ``` ## What a key change does Because matching is by key, a few ordinary edits behave in ways that surprise people: - **Renaming a test or a describe block** gives the calls new keys. Outside CI mode Jest writes fresh entries under the new names and reports the old ones as **obsolete**; an obsolete entry makes the run fail even when every test passed, until `jest -u` removes it. - **Swapping two snapshot calls** inside one test swaps their counters, so both compare against the other's text and both fail. - **A call inside a branch** that runs only sometimes shifts the counter of every later call in that test. - **Deleting a test file** leaves its `.snap` file behind; Jest reports that file as obsolete and deletes it on the next `-u` run. ## Working with the file - Commit the `.snap` file with the code and read its diff in review: it is the assertion. - Prefer descriptive test names, or a hint, over relying on bare counters, so a reviewer can tell from the key alone what the entry should contain. - Keep each serialized value small enough to read; a value nobody reads in review is not checking anything.

  • Why does swapping the order of two toMatchSnapshot calls inside one Jest test break both of them?
    Without a hint, each call is keyed by the test name plus a counter that rises with each call. Swapping the calls swaps which value lands on `name 1` and which on `name 2`, so each one is compared with the other's stored text and both fail. Passing a distinct hint to each call, such as `toMatchSnapshot('first page')`, makes the keys independent of call order.
  • Can a Jest project keep its snapshot files somewhere other than __snapshots__ next to the test?
    Yes. The `snapshotResolver` config key names a module exporting `resolveSnapshotPath(testPath, snapshotExtension)`, `resolveTestPath(snapshotFilePath, snapshotExtension)` and a `testPathForConsistencyCheck` example path. Jest uses it in both directions and uses that example path to check that the two functions invert each other.

  • Jest keeps every snapshot in one shared file at the project root
  • Snapshot entries are matched by their position in the .snap file
  • Renaming a test simply renames its snapshot entry in place
  • The .snap file is a cache and belongs in the ignore list
  • Object keys are stored in the order the code assigned them
open as a page

In Jest 30, how do you update snapshots after an intentional change, and what does jest -u actually rewrite or remove?

level: middleimportance: must knowfreq 62%

basics

~20 s

Run jest -u (--updateSnapshot): it re-records every snapshot that fails in that run, writes missing ones and deletes obsolete entries and orphaned .snap files, so narrow the run with a path pattern or -t first and review the diff.

open as a page

In Jest 30, how does toMatchInlineSnapshot write its snapshot into the test file, and what stops Jest from writing it?

level: middleimportance: should knowfreq 35%

basics

~20 s

On the first run Jest serializes the value, finds the toMatchInlineSnapshot call in the test source and inserts the text as a template-literal argument. It refuses in CI mode, and fails when one call site would need more than one value.

open as a page

In Jest 30, how do you snapshot an object holding a generated id and a timestamp without the snapshot failing on every run?

level: middleimportance: should knowfreq 45%

basics

~20 s

Pass property matchers as the first argument, such as toMatchSnapshot({id: expect.any(String), createdAt: expect.any(Date)}): Jest checks those fields against the matchers, stores the matcher in the snapshot instead of the value and compares the rest exactly.

open as a page

A Jest 30 CI job keeps passing tests whose snapshots were never committed, writing them afresh on every run; why does that happen, and how do you stop it?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Jest only refuses to write a missing snapshot in CI mode, which it detects from environment variables such as CI; if detection fails or -u is passed, the job writes and passes. Run jest --ci explicitly and never pass -u in CI.

open as a page

A Jest 30 snapshot of a rendered config includes an absolute cache path that differs on every machine; how do you fix it with a custom snapshot serializer?

level: seniorimportance: should knowfreq 22%

basics

~10 s

Write a serializer whose test(val) picks strings containing the machine-specific root and whose serialize(...) replaces it and hands the result to printer; register it in snapshotSerializers or with expect.addSnapshotSerializer in that test file.

open as a page