Course contentsShow
← React
Lesson 2154 of 2,39647. Testing Patterns and Best PracticesFree lesson

What Snapshot Tests Actually Do

Snapshots serialize component output to text and fail when it changes, detecting any UI changes without explicit assertions.

What You'll Learn

You'll learn what snapshot tests are, how they work by serializing component output, and why they automatically detect any UI change without writing explicit assertions.

The Core Idea

Snapshot testing takes a picture of your component's rendered output and saves it as a text file. On subsequent test runs, it compares the current output against that saved snapshot. If anything differs—even a single character—the test fails.

Think of it like a security camera for your UI: it captures exactly what your component looked like at a specific moment, then alerts you whenever something changes.

How Snapshots Work

When you create a snapshot test, your testing library (like Jest or Vitest) serializes your component's entire output into a formatted string. This includes:

  • All HTML elements and their structure
  • Props and attributes
  • Text content
  • Class names and styles

This serialized output gets saved to a __snapshots__ directory next to your test file. Every time the test runs afterward, it generates fresh output and compares it character-by-character to the saved version.

What Makes Them Different

Unlike traditional assertions where you explicitly check specific values (expect(button).toHaveTextContent('Submit')), snapshot tests check everything automatically. You don't write assertions about individual elements—the snapshot is the assertion.

When output changes, you review the diff and either:

  • Update the snapshot if the change was intentional
  • Fix your component if the change was a bug

The Trade-off

Snapshots catch any UI change instantly, which is powerful for detecting unintended regressions. However, they can be overly sensitive—changing a single CSS class fails the test. They're also less readable than explicit assertions about user-facing behavior.

Key Takeaway: Snapshot tests serialize your component's complete output to text and fail when anything changes, providing automatic regression detection without writing specific assertions about individual elements.