skip to content

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%

answer

  1. the first argument of the matcher
  2. asymmetric matchers for some fields
  3. checked before the comparison
  4. stored as Any<Date>

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.

solid answer

~40 s

`toMatchSnapshot(propertyMatchers?, hint?)` takes an object of asymmetric matchers for a subset of the received object's properties. Jest first checks those properties the way `toMatchObject` would; if one does not match, the test fails and nothing is written. If they match, Jest stores the matcher in place of the value, so the `.snap` file reads `"createdAt": Any<Date>`, and compares every other field exactly. Matchers can be nested (`{meta: {requestId: expect.stringMatching(/^r-/)}}`), and `toMatchInlineSnapshot(propertyMatchers, snapshot)` works the same way. They only apply to objects: a string or number with matchers fails with `received value must be an object when the matcher has properties`, so a volatile string needs a `replace()`, a custom serializer, or a controlled clock or id source instead.

go deeper

for a junior

Recall that a snapshot of a timestamp or random id fails every run, and that toMatchSnapshot takes matchers like expect.any(Date) for those fields.

for a middle

Explain the order: matchers are checked first, replaced in the stored text, and every other field is still compared exactly; objects only.

for a senior

Choose between property matchers, a serializer, a string replace and controlling the clock or id source, and avoid matchers so loose they assert nothing.

for a principal

Treat widespread loose matchers as a signal that the snapshot no longer pins behaviour, and push for deterministic sources instead.

## Why the plain snapshot fails A snapshot compares the **whole** serialized value. A formatter that stamps each rendered config with a new id and the current time produces different text on every run: ```plaintext - "createdAt": 2026-10-10T10:20:57.326Z, + "createdAt": 2026-10-10T10:21:02.414Z, ``` Updating the snapshot does not help; the next run differs again. The fields are correct, they are just not **stable**. ## Property matchers `toMatchSnapshot` accepts an optional first argument: an object whose values are **asymmetric matchers**, such as `expect.any(Date)`, `expect.any(String)` or `expect.stringMatching(/^cfg_/)`, for a subset of the received object's properties. 1. Jest checks the listed properties against their matchers, with the same subset semantics as `toMatchObject`. 2. If any check fails, the test fails with a diff of `Expected properties` against `Received value`, and **no snapshot is written or compared**. 3. If they pass, Jest substitutes the matcher for the value and serializes the result, so the stored text holds `Any<Date>` rather than a timestamp. 4. Every property **not** listed is compared exactly, as in any snapshot. ```javascript const {randomUUID} = require('node:crypto'); const renderConfig = ({name, retries = 3}) => ({ id: randomUUID(), createdAt: new Date(), name, retries, }); test('renders a config with a generated id', () => { const out = renderConfig({name: 'api'}); expect(out).toMatchSnapshot({ id: expect.any(String), createdAt: expect.any(Date), }); }); ``` ```plaintext exports[`renders a config with a generated id 1`] = ` { "createdAt": Any<Date>, "id": Any<String>, "name": "api", "retries": 3, } `; ``` ## Details that matter - **Nesting works.** `{meta: {requestId: expect.stringMatching(/^r-/), createdAt: expect.any(Date)}}` stores a `StringMatching` entry and `Any<Date>` inside `meta`. - **A plain value in the matcher object is checked exactly** and saved, so listing `name: 'api'` is legal but adds nothing over the snapshot itself. - **Inline snapshots take the same argument first**: `toMatchInlineSnapshot({createdAt: expect.any(Date)})`, and Jest writes the snapshot text as the second argument. - **A hint goes second**: `toMatchSnapshot({createdAt: expect.any(Date)}, 'with defaults')`. - **Objects only.** Passing matchers with a string, number or other primitive fails with a matcher error, `received value must be an object when the matcher has properties`. ## What each matcher leaves in the file The stored text records which matcher stood in for the value, so a reviewer can see how loose each field is: | Matcher in the first argument | Printed in the snapshot | |---|---| | `expect.any(Date)` | `Any<Date>` | | `expect.any(String)` | `Any<String>` | | `expect.anything()` | `Anything` | | `expect.stringMatching(/^cfg_/)` | `StringMatching` followed by the pattern | | `expect.objectContaining({x: 1})` | `ObjectContaining` followed by the listed properties | ## When the volatile part is inside a string Property matchers cannot reach into a string such as `Config cfg_8f3a saved at 10:21`. The options are: | Approach | How it works | Cost | |---|---|---| | Replace before asserting | `text.replace(/cfg_\w+/, 'cfg_<id>')` | local and obvious, repeated in each test | | Custom snapshot serializer | a serializer's `test` picks such strings and `serialize` normalizes them | set once, hides the rule from the test | | Control the source | mock the id generator, or fix the clock with fake timers | removes the volatility rather than masking it | ## Choosing a matcher that still asserts something - `expect.any(Date)` proves the field is a `Date`; it says nothing about **which** date. If the value matters, assert it separately or control the clock. - `expect.stringMatching(...)` keeps a format check, which is stronger than `expect.any(String)` for an id with a known shape. - `expect.anything()` accepts anything except `null` and `undefined`; reaching for it on many fields is a sign the snapshot is checking very little. Property matchers are for fields that are **correctly different each time**. A field that changes because the code is nondeterministic by mistake should be fixed, not matched. ## A quick decision order 1. **Can the test control the source?** Inject the id generator or fix the clock; the snapshot then stores real, stable values and checks them exactly. 2. **Is the field correctly different on each run, and a property of an object?** Use a property matcher, as tight as the field allows. 3. **Is the varying part inside a string?** Replace it in the test, or register a serializer when many tests share the problem.

  • In Jest, what happens when a property matcher fails, for example createdAt arrives as a string while the matcher is expect.any(Date)?
    The test fails before any snapshot work: Jest prints a diff of `Expected properties` against `Received value` showing `Any<Date>` against the string. Nothing is written, even on the first run, and `-u` cannot paper over it, because the property check is an ordinary assertion rather than part of the stored snapshot.
  • Can you use property matchers with toMatchInlineSnapshot in Jest?
    Yes. Pass the matcher object as the first argument and leave the snapshot out; on the first run Jest writes the serialized text, with `Any<Date>` in place of the value, as the second argument in the test source. Later runs check the matchers first and then compare the rest with that literal.

  • Property matchers skip the listed fields, so their type is never checked
  • Running jest -u on every run is how you handle volatile fields
  • Property matchers also work on a string with an embedded timestamp
  • A failing property matcher still writes the snapshot on the first run
  • Fields left out of the matcher object are ignored by the snapshot