Skip to content
BENIBIX Learn

Snapshot Test

Development🧪 Testing & QualityTest Types

Also known as Snapshot Testing, toMatchSnapshot

A test that saves some output once, then fails if it ever changes.

Think of it like

Think of it like a photo of your room. Next time, you spot what moved.

Example

Jack's snapshot test saves the HTML of his price box. When a change drops the currency sign, the test fails and shows the missing pound sign.

Why it matters

It catches changes nobody meant to make. You do not have to write a check for every detail.

Definition

A snapshot test saves the output of some code the first time it runs. Later runs are compared against it. The output might be a chunk of HTML, a JSON reply or a picture. If anything changes, the test fails and shows the difference. You then either fix the bug or accept the new output as the new snapshot. Jest made the idea popular with toMatchSnapshot.

Example code

javascript
test('price box', () => {
  expect(render(price)).toMatchSnapshot();
});
The first run saves the output; later runs must match it.

Common mistake

Accepting each new snapshot without reading what changed. Then the test lets bugs through.

Key takeaways

  1. 1
    Save once. The first run is the answer.
  2. 2
    Fail on any change. And show the difference.
  3. 3
    Read before you accept. Or it means nothing.