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

What Are Snapshot Tests?

Learn how snapshot tests capture and compare output to detect unintended changes over time.

What Are Snapshot Tests?

You'll learn how snapshot tests work as an automated "freeze frame" to catch unintended changes in your code's output over time.

The Core Idea

Snapshot tests capture the entire output of a function or component at a given moment and save it as a reference file. On subsequent test runs, the test runner compares the current output against that saved snapshot. If anything differs—even a single character—the test fails, alerting you to potential breaking changes.

Think of it like taking a photograph of your code's output. The first time you run the test, you take the photo. Every time after, you compare the current state to that original photo. If someone repainted a wall or moved furniture, you'd notice immediately.

How They Work in Practice

When you write a snapshot test, you call a matcher like toMatchSnapshot() on your output:

const result = formatUserProfile({ name: "Alice", age: 30 });
expect(result).toMatchSnapshot();

The first run creates a snapshot file containing the exact output. Future runs compare against this file. If the output changes intentionally (like a feature update), you manually update the snapshot. If it changes accidentally (like a bug), the test catches it.

When to Use Snapshots

Snapshot tests excel at detecting unexpected changes in complex output like:

  • Rendered HTML structures
  • Large configuration objects
  • Error messages
  • Serialized data formats

They're particularly valuable when the exact output structure matters but would be tedious to assert manually with dozens of individual assertions.

Key Takeaway: Snapshot tests act as a safety net by preserving "known good" output and alerting you whenever something deviates from that baseline, making regression detection effortless.