Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 39 ยท Documentation and Testing

Contract Testing and Mock Servers

Learn consumer-driven contract tests, provider verification, mock servers built from a spec, and fault injection so clients are ready for slow or failing APIs.

Unit tests prove your code works. Integration tests prove your pieces work together. But when a frontend team, a mobile app and three other services all call your API, a new question appears: do both sides still agree on the contract? If the backend renames total to totalAmount, every test on the backend can pass while the app crashes in production.

Contract testing checks the agreement between a consumer (the client) and a provider (the API) without needing both to run together in a slow end-to-end environment. Its companion technique, mock servers, lets a client team build and test against an API that does not exist yet, or that is slow, expensive or flaky. This lesson shows both.

Consumer-driven contracts

Consumer writes I need id and total.
Contract A shared file of expectations.
Provider verifies Replays it against the real API.
CI gate A breaking change fails the build.

Each consumer states only what it really uses.

1 / 2

Why end-to-end tests are not enough

An end-to-end test starts every service, uses real data, and clicks through a scenario. It finds real integration bugs, but it is slow, flaky, hard to debug ("which of the six services broke?") and tells you late. You need only a few of them. The bulk of your safety should come from fast checks that each side honors the shape of the messages.

The contract idea

A contract lists example interactions: "when I send this request, I expect a response with this status and a body with these fields and types". It deliberately describes types and structure, not exact values, because values change.

The workflow of consumer-driven contract testing (the approach of the Pact tool family):

  1. The consumer team writes tests against a mock provider. While they pass, the library records every request and expected response into a contract file.
  2. The contract is shared (through a broker or the repository).
  3. The provider team replays each recorded request against the real API in its own CI and checks that the real response satisfies the expectations.
  4. If a provider change would break a consumer, the provider's build fails before deploying, and the message names the consumer and the field.

Because every consumer lists only the fields it actually reads, the provider is free to change everything else.

Node.js A minimal consumer contract check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The verification of the new release fails with exact messages (total missing, status has the wrong type), and it ignores createdAt because the consumer never listed it. This is the safety net that lets teams deploy independently.

Mock servers

A mock server returns canned responses. Reasons to use one:

  • The real API is not built yet. Front-end and back-end teams agree on an OpenAPI spec (Documenting APIs with OpenAPI) and the front end builds against a mock generated from it.
  • You need a stable target for tests: no network, no rate limits, no cost.
  • You must test conditions that are hard to trigger on demand: a 503, a timeout, a 429, a malformed body, a slow response.
  • A third-party sandbox is unreliable or lacks the scenarios you need.

Tools generate mocks from a spec (Prism, WireMock, MockServer, Mockoon, MSW for browser and Node). The important design points are the same everywhere: serve the examples in the spec, validate the incoming request against it, and let tests add overrides for special cases.

Node.js A mock server with fault injection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Without fault injection you would never know if your retry logic works until the real provider has an outage.

Provider-driven contracts and schema checks

Consumer-driven contracts are one option. In others, the provider publishes its OpenAPI spec as the contract and both sides test against it:

  • Provider side: run the API's tests and validate every real response against the spec's schemas, so the spec cannot lie. Tools like Schemathesis generate requests from the spec and check the responses.
  • Consumer side: generate typed clients from the spec, and run mocks generated from it.
  • CI gate: diff the spec against the released version and fail on breaking changes (API Versioning and Evolution).

Both approaches work. Consumer-driven contracts shine for internal services with a few known consumers. Spec-first approaches fit public APIs with many unknown consumers.

Good habits

  • Make contracts about structure and types, not exact data, and include error responses (404, 422, 401).
  • Keep mocks honest: verify them against the real API regularly (that is what the provider verification does), or they will drift.
  • Version and store contracts with the code, and publish verification results so teams can see who depends on what.
  • Treat a failed contract as a conversation between teams, not just a red build.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does contract testing check?

    Contract tests verify the agreement between two sides without running a full end-to-end environment.
  2. 2. In consumer-driven contracts, who writes the expectations?

    Consumers record what they rely on, so providers know exactly what they must not break.
  3. 3. Why does the contract describe types instead of exact values?

    Checking that total is a number stays valid when the amount changes.
  4. 4. What is fault injection in a mock server?

    It lets you test retries, timeouts and error handling without waiting for a real outage.
  5. 5. Why are only a few end-to-end tests recommended?

    End-to-end tests are valuable but expensive, so keep a small set and rely on contract and integration tests for the rest.

Summary

  • Contract tests verify that consumer and provider agree on request and response shape, without a full environment.
  • In consumer-driven contracts, consumers record the fields they use and the provider replays them in CI.
  • Describe types and structure, include error cases, and fail the provider's build on a break.
  • Mock servers give stable, fast targets and let you inject faults (503, 429, timeouts) to test client resilience.
  • Spec-first teams validate responses against the OpenAPI spec and diff the spec between releases.

Next: Project: A Secure Notes API