← Recipes

阅读中文版本

Snapshot REST API Contracts

Capture normalised response snapshots for REST endpoints so unintended contract changes fail review instead of reaching clients.

~30 mintestingapicontract

Task

Add response snapshot tests that ignore volatile fields but catch contract changes.

When to use this

A field is renamed in a response and clients break, because no test treats the response shape as a contract.

Prerequisites

  • A test runner with snapshots
  • A running API or mocked handler
  • A list of volatile fields to normalise

Steps

1. Normalise volatile fields then snapshot the response.

const res = await request(app).get('/api/users/1');
const stable = { ...res.body, id: '<id>', createdAt: '<ts>' };
expect(stable).toMatchSnapshot();

Expected output: Snapshots capture the shape while ignoring ids and timestamps.

2. Update snapshots only through review.

npx vitest run -u
# review the snapshot diff in the pull request before merging

Expected output: Any response shape change shows as a snapshot diff a reviewer must approve.

Troubleshooting

Problem

Snapshots updated blindly

Solution

Require reviewers to inspect snapshot diffs and forbid blanket -u in CI.

Problem

Volatile fields noisy

Solution

Normalise all generated ids and timestamps before comparing.

Limitations

  • Snapshots do not validate semantics.
  • Large snapshots are hard to review.
  • Not a substitute for schema validation.

What this recipe does

Add response snapshot tests that ignore volatile fields but catch contract changes.

A field is renamed in a response and clients break, because no test treats the response shape as a contract.

Prerequisites

  • A test runner with snapshots
  • A running API or mocked handler
  • A list of volatile fields to normalise

Procedure

  1. Normalise volatile fields then snapshot the response.
const res = await request(app).get('/api/users/1');
const stable = { ...res.body, id: '<id>', createdAt: '<ts>' };
expect(stable).toMatchSnapshot();

Expected result: Snapshots capture the shape while ignoring ids and timestamps.

  1. Update snapshots only through review.
npx vitest run -u
# review the snapshot diff in the pull request before merging

Expected result: Any response shape change shows as a snapshot diff a reviewer must approve.

How to confirm it worked

Run the commands above and confirm every expected result in order. If a step does not produce the stated output, use the troubleshooting notes before continuing. A passing run shows renaming a response field fails the snapshot test until the snapshot is deliberately reviewed and updated.

Troubleshooting

Snapshots updated blindly — Require reviewers to inspect snapshot diffs and forbid blanket -u in CI.

Volatile fields noisy — Normalise all generated ids and timestamps before comparing.

Limitations

  • Snapshots do not validate semantics.
  • Large snapshots are hard to review.
  • Not a substitute for schema validation.