Contract Testing

Contract testing makes sure two sides keep agreeing on the shape of the data: which fields (items of the data) there are and what type each one has. That…

The shop's production page (the real site buyers use) suddenly greets buyers with "Hi, undefined". The frontend tests (for the part shown in the browser) are green, and so are the backend tests (for the server that sends the data). The problem sits between the two: the backend renamed one field (one item of the data, such as name), and the frontend never found out.

Contract testing guards that gap. It makes sure two systems that exchange data, such as a frontend and a backend, keep agreeing on the shape of the data: which fields there are, and what type each one has. That agreement is called the contract. Picture ordering catering for an event. You write the order list: boxed rice, chicken and chilli sauce. The kitchen may add crackers without telling you, but if the chicken is swapped for fish, your event is a mess. Before delivery, the kitchen checks its food against that list. In this picture, you are the frontend that uses the data, the kitchen is the backend that serves it, and the order list is the contract. The crackers are an extra field, and chicken swapped for fish is a field whose name or type changed.

Why a contract

Two apps, two repos (where a project's code is stored), two teams:

One day the backend team renames the field name to fullName. The backend's unit tests stay green, because that team changed the tests along with it. The frontend's unit tests are green too, because there the API response is mocked (replaced with a stand-in), and that stand-in still holds name. Then both are deployed, and the production page shows "Hi, undefined". An integration or E2E test could catch it, but it needs both systems running together, so it's slow and costly. A contract test catches it in each repo's own CI, without running both systems at once.

The consumer writes the contract

The most common approach is called a consumer-driven contract (a contract the consumer decides): the consumer writes down what it needs, then the provider proves it delivers that. The most popular tool for this is Pact. This is the web-shop function that fetches a user's data:

// web-shop: src/api.js
export async function getUser(baseUrl, id) {
  const res = await fetch(`${baseUrl}/api/users/${id}`);
  return res.json();
}

Then its Pact test, which also writes the contract:

// web-shop: src/api.pact.test.js
import { PactV3, MatchersV3 } from "@pact-foundation/pact";
import { it, expect } from "vitest";
import { getUser } from "./api.js";

const { like } = MatchersV3;
const provider = new PactV3({ consumer: "web-shop", provider: "api-user" });

it("fetches user 1", () => {
  provider
    .given("user 1 exists")
    .uponReceiving("a request for user 1")
    .withRequest({ method: "GET", path: "/api/users/1" })
    .willRespondWith({
      status: 200,
      body: like({ id: 1, name: "Budi", email: "[email protected]" }),
    });

  return provider.executeTest(async (mockServer) => {
    const user = await getUser(mockServer.url, 1);
    expect(user.name).toBe("Budi");
  });
});

The provider verifies the contract

In the api-user repo, Pact sends every request from the pact file again to the real provider, then matches the responses against the contract. This step is called provider verification.

// api-user: test/pact.verify.test.js
import { Verifier } from "@pact-foundation/pact";
import { it } from "vitest";

it("honours the web-shop contract", () => {
  return new Verifier({
    provider: "api-user",
    providerBaseUrl: "http://localhost:3000",
    pactUrls: ["./pacts/web-shop-api-user.json"],
    stateHandlers: {
      "user 1 exists": async () => {
        // put user 1 into the test database
      },
    },
  }).verifyProvider();
});

providerBaseUrl is the address of the running provider, and pactUrls points at the pact file. stateHandlers sets up each provider state, for example putting user 1 into the test database for "user 1 exists".

Think about one case first: the backend adds a new field phone to the response of GET /api/users/1, and the frontend doesn't use it. Does the contract verification pass or fail?

Provider response Verification result
{ id: 1, name: "Budi", email: "[email protected]" } passes
the same, plus phone: "081234567890" passes
name renamed to fullName fails: the name field is missing
id becomes the string "1" fails: its type is no longer a number

The verification passes, as in the table's second row. The extra field phone breaks nothing: Pact only checks the fields the consumer wrote in the contract, and other fields are ignored. What breaks a contract is removing or renaming a field that's needed, or changing its type. This is Pact's output when name is renamed to fullName:

Verifying a pact between web-shop and api-user

  a request for user 1 (0s loading, 12ms verification)
     Given user 1 exists
    returns a response which
      has status code 200 (OK)
      has a matching body (FAILED)

Failures:

1) Verifying a pact between web-shop and api-user Given user 1 exists - a request for user 1
    1.1) has a matching body
           $ -> Actual map is missing the following keys: name

There were 1 pact failures

$ is the whole response body. Actual map is missing the following keys: name means the real body has no field name. If id turns into a string, that line starting with $ reads $.id -> Expected '1' (String) to be the same type as 1 (Integer): the field id should be a number. A failed verification turns the provider's CI red before the change reaches production.

New needs take the same route. If the frontend starts needing avatarUrl, the consumer adds it to the contract first. Verification on the provider fails until the backend serves that field. Meanwhile, the Pact Broker's pact-broker can-i-deploy command stops the frontend from being deployed first, because its new contract hasn't passed the provider's verification yet.

A lighter way: schema validation

If you aren't ready for Pact, you can check the shape of a response with a schema library such as Zod. A schema is a description of the shape you expect.

import { z } from "zod";

const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string(),
});

const data = await getUser("http://localhost:3000", 1);
const parsed = UserSchema.parse(data); // throws a ZodError when the shape doesn't match

⚠️ Contracts that are too strict or written by the wrong side

TL;DR: Contract testing makes sure two sides keep agreeing on the shape of the data: which fields (items of the data) there are and what type each one has. That agreement is called the contract. The consumer is the side that uses the data, such as a frontend, and the provider is the side that serves it, such as a backend. In a consumer-driven contract, the consumer writes the contract. With Pact (a contract testing tool), the consumer's test runs against a mock server (a pretend server) and produces a pact file (the contract file). Then on the provider's side, Verifier sends the requests from that file again to the real API and matches the responses. Use like so the type is checked, not the value. Extra fields on the provider are safe, but removing, renaming or retyping a field that's needed fails verification in CI. A lighter way: check the response with a schema library (a checker for the shape of data) such as Zod, UserSchema.parse(data), which throws an error when the shape doesn't match.

⚡ A contract between consumer and provider

Meaning: The consumer (the frontend web-shop) uses the data, and the provider (the backend api-user) serves it. Contract testing makes sure the two keep agreeing on the shape of the data: which fields (items of the data, such as name) there are and what type each one has. That agreement is called the contract. If the provider breaks it, the break shows up in each repo's own CI, without running both systems together.

⚡ The consumer writes the contract

Write:

.willRespondWith({
  status: 200,
  body: like({ id: 1, name: "Budi", email: "[email protected]" }),
});

Meaning: This is part of a consumer test with Pact, a contract testing tool. willRespondWith(...) writes down the response the consumer needs, and that part becomes the contract. like(...) matches the type, not the value: id must be a number, name and email must be strings. The provider may return "Siti"; what matters is that it's a string.

⚡ Extra fields are safe

Guess first: during verification, Pact matches the provider's real response against the contract. The backend adds a field phone the frontend doesn't use. Does the contract verification pass or fail?

It passes. Pact only checks the fields the consumer wrote in the contract, and other fields are ignored.

Meaning: What breaks a contract is removing, renaming or retyping a field that's needed, for example name becoming fullName.

What you will learn