Code Reference

Snapshots

Jest · Reference cheat sheet

Snapshots

Jest · Reference cheat sheet


📋 Overview

Snapshots store serialized output and fail when it changes. Use for UI trees, large JSON, or error messages — keep them small and review diffs in PRs.

🔧 Core concepts

APIUse
toMatchSnapshotFile under __snapshots__
toMatchInlineSnapshotEmbedded in test file
toThrowErrorMatchingSnapshotError text
-u / --updateSnapshotRefresh baselines
Property matchersSoften volatile fields

Prefer inline snapshots for tiny values; file snapshots for larger trees.

💡 Examples

Basic:

test('renders', () => {
  expect(renderHeader()).toMatchSnapshot();
});

Inline:

expect(user).toMatchInlineSnapshot(`
{
  "id": 1,
  "name": "Ada",
}
`);

Property matchers:

expect(article).toMatchSnapshot({
  id: expect.any(Number),
  createdAt: expect.any(Date),
});

Update:

npx jest -u
npx jest path/to/file.test.js -u

Serializer (custom):

expect.addSnapshotSerializer({
  test: (v) => v && v.__type === 'Money',
  print: (v) => `Money(${v.cents})`,
});

⚠️ Pitfalls

  • Giant DOM snapshots that churn on class-name noise.
  • Blindly updating with -u without reading diffs.
  • Timestamps/random IDs without property matchers.
  • Committing snapshots that differ by OS line endings.
  • Using snapshots instead of precise matchers for critical logic.

On this page