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?
answer
- normalize at print time
- test picks, serialize prints
- printer for the rest
- config list or per-file call
basics
~10 sWrite 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.
solid answer
~40 sA snapshot serializer is a `pretty-format` plugin: an object with `test(val)`, which says whether it handles a value, and `serialize(val, config, indentation, depth, refs, printer)`, which returns the text. For a path that differs per machine, `test` matches strings containing the project root and `serialize` replaces the root with a placeholder, then calls `printer` so the result is quoted and indented like any other string; since the new string no longer matches `test`, the recursion ends after one step. Register it for the whole project with the `snapshotSerializers` config key, or for one file with `expect.addSnapshotSerializer`. A per-file serializer is tried before configured ones, which come before the built-in serializers, and the last one added is tried first. It applies to file and inline snapshots alike, so `"cacheDir": "<rootDir>/.cache"` is now the same everywhere.
code
javascript · 3 linesmodule.exports = {
snapshotSerializers: ['<rootDir>/test/path-serializer.js'],
};go deeper
Recall that Jest lets you register a snapshot serializer to change how values are printed in snapshots.
Explain test versus serialize, delegating to printer, and registering through snapshotSerializers or expect.addSnapshotSerializer.
Fix machine-dependent snapshots with a narrow serializer, explain the precedence order and the recursion guard, and pick it over matchers when the variation sits inside a string.
Keep shared serializers few and narrow; one that normalizes too much quietly turns many snapshots into checks of nothing.
## The problem The config formatter resolves paths, so its output contains the directory the suite runs from: ```plaintext - "cacheDir": "/home/dev-a/app/.cache", + "cacheDir": "/builds/app/.cache", ``` Every machine records a different snapshot, and every other machine fails it. The path is **correct**, it is just not **portable**. Property matchers do not fit well: the volatile part sits inside a string, and `expect.any(String)` would stop checking the part that matters, the `.cache` suffix. ## What a serializer is Jest serializes snapshot values with `pretty-format`. A **snapshot serializer** is a `pretty-format` plugin, an object with two methods: - **`test(val)`** is called with values as they are printed, of any type, and returns truthy when this plugin should print it. Guard it (`typeof val === 'string' && ...`, or `val && ...` for objects), because it also receives `null` and `undefined`, and keep it cheap, because it is called often. - **`serialize(val, config, indentation, depth, refs, printer)`** returns the text. `printer` serializes a child value with every registered plugin, so a serializer can delegate rather than format by hand. `pretty-format` also accepts an older interface with `print(val, printer, indenter, config, colors)` in place of `serialize`; new serializers use `serialize`. ## A serializer for the path ```javascript const root = process.cwd(); module.exports = { test(val) { return typeof val === 'string' && val.includes(root); }, serialize(val, config, indentation, depth, refs, printer) { return printer(val.replaceAll(root, '<rootDir>'), config, indentation, depth, refs); }, }; ``` Three details make it work: 1. It **narrows** to strings that contain the root, so every other value prints normally. 2. It **delegates** the rewritten string to `printer`, so quoting, escaping and indentation match the rest of the snapshot. 3. The rewritten string no longer contains the root, so `test` rejects it on the way back through `printer` and the call **does not recurse forever**. The snapshot then reads `"cacheDir": "<rootDir>/.cache"` on every machine. ## Registering it | Where | How | Scope | |---|---|---| | Jest config | `snapshotSerializers: ['<rootDir>/test/path-serializer.js']` | every test file in the project | | One test file | `expect.addSnapshotSerializer(require('./path-serializer'))` | that file only | Order of precedence when Jest prints a value: 1. Serializers added with `expect.addSnapshotSerializer` in the file, **the last one added tried first**. 2. Serializers listed in `snapshotSerializers`. 3. The built-in serializers for JavaScript types, DOM elements and other built-in structures. The first plugin whose `test` returns truthy wins. The per-file call makes the dependency **visible in the test**; the config key keeps every file consistent. Either way it applies to `toMatchSnapshot`, `toMatchInlineSnapshot` and the error-snapshot matchers. ## Serializer or something else - **`snapshotFormat`** changes `pretty-format` options for the whole project (its default is `{escapeString: false, printBasicPrototype: false}`); it formats, it does not rewrite values. - **A string `replace()` in the test** is fine for one test and becomes repetition across fifty. - **Removing the source of variation**, for instance passing the root into the formatter as an argument and fixing it in tests, is often the cleanest option of all. ## Rolling it out - Adding a serializer changes how values **print**, so snapshots recorded before it existed no longer match. Run a targeted `jest -u` once, and check that the diff shows only the paths turning into `<rootDir>`. - A serializer listed in `snapshotSerializers` is resolved as a module path; `<rootDir>` in that path keeps it independent of the directory Jest is started from. - If nothing changes after registration, the usual causes are a `test` that never matches (for example comparing against a root with a different separator or a trailing slash) or a serializer added in a different test file. - A serializer whose rewritten value still matches its own `test` recurses until the stack overflows, so test the serializer on a small value first. ## Keeping a serializer honest - Normalize only what is **genuinely environmental**: paths, temp directories, line endings, generated ids. - Keep the replacement **recognizable** (`<rootDir>`, `<tmp>`), so a reviewer can tell normalization from data. - Test the serializer itself with a small snapshot, and remember that a broad `test` can hide a real change: a serializer that blanks every string containing a digit makes most snapshots meaningless.
- Why does a Jest serializer that calls printer on its own output not recurse forever?`printer` runs the value through every registered plugin again, including this one. It stops because `serialize` changes the value so that `test` no longer matches it: the rewritten string has no project root left in it. A serializer whose rewritten value still satisfies its own `test` would call itself again and again, so the transformation must leave the matched condition behind.
- In Jest, if both a configured serializer and one added with expect.addSnapshotSerializer match the same value, which one prints it?The one added in the test file. Serializers added with `expect.addSnapshotSerializer` are tried before those in `snapshotSerializers`, which are tried before the built-in ones, and among per-file additions the last one added is tried first. The first plugin whose `test` returns truthy prints the value.
- Configured serializers run before ones added in the test file
- A serializer must format nested values by hand without printer
- Serializers only apply to file snapshots, not inline ones
- snapshotFormat is where you rewrite machine-specific values
- expect.any(String) on the path keeps the suffix checked