Course contentsShow
← JavaScript
Lesson 2708 of 2,72354. Testing in JavaScriptFree lesson

Creating Your First Snapshot

Use toMatchSnapshot() to create a baseline snapshot file that stores expected output.

Creating Your First Snapshot

You'll learn how to capture your first snapshot with toMatchSnapshot() and understand what happens behind the scenes.

The Core Idea

When you call toMatchSnapshot() in a test, your test runner (like Jest or Vitest) takes the value you're testing and saves it to a special file called a snapshot file. This file becomes your "source of truth" — a baseline that future test runs compare against.

Think of it like taking a photograph of your living room. The first time, you snap the picture and file it away. Every time you return home, you compare the room to that photo. If something's moved, you notice immediately.

Creating Your First Snapshot

// sum.js
function formatSum(a, b) {
  return `The sum of ${a} and ${b} is ${a + b}`;
}

// sum.test.js
test('formatSum creates correct message', () => {
  const result = formatSum(5, 3);
  expect(result).toMatchSnapshot();
});

What happens on the first run:

  1. Jest executes your test
  2. Captures the value: "The sum of 5 and 3 is 8"
  3. Creates a __snapshots__ folder next to your test file
  4. Saves the output to sum.test.js.snap
  5. The test passes (snapshot created successfully)

On subsequent runs: Jest compares the current output against the saved snapshot. If they match, the test passes. If they differ, the test fails and shows you the difference.

The Snapshot File

Jest automatically creates a human-readable snapshot file:

exports['formatSum creates correct message 1'] = `"The sum of 5 and 3 is 8"`;

You should commit this file to version control alongside your tests.

Key Takeaway: toMatchSnapshot() creates a baseline file the first time it runs, storing your expected output for automatic comparison in all future test runs.