A snapshot test saves some output to a file, then fails whenever that output changes later.
How it works:
- The test serialises output, such as a rendered component's DOM, into text.
- The first run saves it to a file.
- Later runs compare against that file.
- Any difference fails the test until someone updates the snapshot with
jest -u.
Pros: snapshots are almost free to write, and they catch unexpected output changes.
Cons:
- They don't say what is correct, only that something changed.
- Large component snapshots break on every harmless markup change.
- So people get used to updating them without reading the diff. Then the test stops protecting anything.
Use them for small, stable output where the exact value matters. Examples are a serialised config, an error message or a small piece of markup. Prefer toMatchInlineSnapshot(), so the expected value sits inside the test and gets reviewed. For components, explicit assertions on behaviour are better.
- A snapshot test saves output and compares future runs to it.
- Snapshots are cheap and catch unexpected changes.
- Snapshots don't define what correct behaviour is.
- Large snapshots get updated without anyone reading the diff.
- Keep snapshots small, and prefer inline snapshots.
Read more