Skip to main content

What is snapshot testing?

Snapshot testing is a testing method in which the current representation of the result is captured (for example, a component's markup, an object or a string), and on subsequent test runs this result is compared with the saved snapshot. If the result has changed, the test fails.


How this works, essentially

  1. The test runs for the first time and saves a "snapshot" of the result to a separate file, the snapshot.
  2. On subsequent test runs, Jest generates the result again.
  3. If the new result exactly matches the snapshot, the test is green.
  4. If not, Jest reports that the behavior has changed.

When this is useful

  • when testing React components (JSX markup)
  • when testing complex objects that are inconvenient to check by hand
  • when the structure of the result matters, not individual fields

What a snapshot gives you

  • lets you notice unexpected changes in the UI or data
  • speeds up testing of complex structures
  • acts as a "checkpoint" of the current state of a component or function

Example (general idea)

If a component used to return this markup:

html
<button>Send</button>

and after a code change started returning:

html
<button>Send message</button>

the snapshot test will catch this, because the markup no longer matches the saved snapshot.


The main idea

Snapshot testing is an automatic capture and control of changes in the result, so the developer knows in advance exactly what has changed and whether this is expected behavior.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.