In Jest 30, where does toMatchSnapshot store a snapshot, and how is each entry in that file named and matched?
answer
- a folder beside the test file
- one .snap file per test file
- describe and test names joined
- a counter that restarts in each test
basics
~20 stoMatchSnapshot 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 sThe 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 linesconst 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
Recall the snapshots folder beside the test, one .snap file per test file, and that the file is committed and reviewed with the code.
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.
Show you can diagnose snapshot failures that come from keys rather than output: swapped calls, conditional calls, renamed blocks and orphaned files.
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