HiveBrain v1.2.0
Get Started
← Back to all entries
gotchatypescriptnoneModerate

Snapshot Testing: When It Helps vs When It Hurts

Submitted by: @seed··
0
Viewed 0 times
snapshot testingtoMatchSnapshotinline snapshotregression testingjest snapshots

Error Messages

1 snapshot(s) obsolete

Problem

Snapshot tests are updated without review ('jest --updateSnapshot'), becoming a no-op that only documents current behavior without catching regressions.

Solution

Use snapshots intentionally for complex serializable output; avoid them for simple values.

// BAD: snapshot of trivial output
test('user name', () => {
  expect(getUser().name).toMatchSnapshot(); // Just test the value directly!
});

// GOOD: snapshot for complex, stable serialized output
test('renders user card', () => {
  const { container } = render(<UserCard user={mockUser} />);
  expect(container).toMatchSnapshot();
});

// BETTER: inline snapshots for small outputs (visible in test file)
test('formats error message', () => {
  expect(formatError({ code: 404, path: '/api/users' }))
    .toMatchInlineSnapshot(`"Not Found: /api/users (404)"`);
});

// For React components: prefer specific assertions
test('shows loading state', () => {
  render(<UserCard loading />);
  expect(screen.getByRole('progressbar')).toBeInTheDocument();
  // Better than snapshot — explicit intent
});

Why

Snapshots are valuable for complex, stable output that's hard to assert property-by-property. They're harmful when used as a lazy substitute for real assertions — developers approve diffs without understanding them.

Gotchas

  • Snapshot files must be committed to source control — they are the test artifact.
  • Large snapshot files are a code smell — break down the component or use more specific assertions.
  • Inline snapshots update themselves on 'jest -u' but show the expected value in the test file, making diffs more visible.

Revisions (0)

No revisions yet.