How-To Guide

How to Implement Contract Tests Between Services

Test the contract between services: define the expected request and response, verify the provider against it, and catch drift before deploy.

On this page

  1. Introduction
  2. Define the contract from what consumers rely on
  3. Verify the provider against the contract
  4. Stub the provider for the consumer
  5. Version the contract with the API
  6. Test both directions and the failure cases
  7. Common pitfalls
  8. Conclusion

Introduction

Two services that talk to each other share a contract: the request one sends and the response the other returns. When each is tested only in isolation, a change on one side can break the other in production, because nothing checked the agreement. An integration test that runs both catches it but is slow and couples the two deployments. A contract test checks the agreement directly: the provider is verified to satisfy it, and the consumer against a stub from it.

This tutorial defines a contract, verifies the provider against it, uses a stub for the consumer, and versions it with the API. The examples use HTTP services, and the approach applies to any request-response interface.

Define the contract from what consumers rely on

The contract is not the full API; it is what the consumers actually depend on. A consumer that reads order.id, order.total, and a 404 for a missing order relies on those, not on every field the provider returns. Write the contract as those expectations: the request the consumer makes, the fields it reads, the types, and the status codes and error shapes it branches on.

Keeping the contract to what is used keeps it small and meaningful. A contract that pins every field makes the provider unable to add one without a version bump, which is the opposite of what you want. The contract should encode the dependencies, so the provider can evolve freely in the parts no consumer uses and is stopped only when it would break a dependency.

// consumer expectation recorded as a contract
const contract = {
  request: { method: 'GET', path: '/orders/42' },
  response: {
    status: 200,
    body: {
      id: 42,                 // the consumer reads these fields
      total: expect.any(Number),
      status: expect.stringMatching(/^(pending|paid)$/),
    },
  },
};

// a consumer test that fails if the contract changes incompatibly
test('consumer handles the order response', async () => {
  const client = makeClient(stubFrom(contract));
  const order = await client.getOrder(42);
  expect(order.total).toBeGreaterThanOrEqual(0);   // the consumer's expectation
});

Verify the provider against the contract

The provider runs the contract against its real implementation: for each contract, it sends the recorded request and asserts the response matches the recorded expectation. If the provider stops returning a field a consumer reads or changes a status code a consumer branches on, the provider’s build fails, before the change reaches production.

Run the provider verification in the provider’s pipeline, so a breaking change is caught where it is introduced. The contract is the test, and the provider cannot merge a change that violates it. This shifts the detection from an integration test in production-like staging to a fast check in the provider’s own build, which is earlier and cheaper.

// provider verification: send the recorded request, match the expectation
for (const c of contracts) {
  const res = await app.request(c.request);          // the real provider
  expect(res.status).toBe(c.response.status);
  for (const [key, matcher] of Object.entries(c.response.body)) {
    expect(res.body[key]).toEqual(matcher);          // a missing field fails here
  }
}

Stub the provider for the consumer

The consumer’s tests run against a stub generated from the contract, so the consumer is tested against the agreed shape rather than a hand-written mock that can drift. When the contract changes, the stub changes, and the consumer’s tests either pass (the change is compatible) or fail (the consumer relied on something removed). This catches the drift on both sides.

A stub from the contract is better than a hand-maintained mock because it cannot silently diverge: it is derived from the same source the provider is verified against. If the contract is generated by the consumer’s tests, the consumer defines what it needs, and the provider must satisfy it, which is the consumer-driven model. Either way, one source of truth for the shape.

Version the contract with the API

A contract is a version of the API from a consumer’s perspective. When a breaking change is needed, add a new contract version alongside the old, keep the provider serving both during migration, and retire the old version when its consumers have moved. This mirrors API versioning, and it keeps the detection working across the migration period.

Record which consumer wrote which contract, so a change that breaks one is attributed and can be coordinated. A contract written by a consumer that no longer exists should be retired, or it blocks provider changes for nothing. Treat the contracts as part of the API’s public surface, reviewed and maintained, not as test artifacts that drift.

Test both directions and the failure cases

Test the happy path, where the provider satisfies the contract, and the failure case, where a removed field or a changed status fails the provider’s verification. Test a compatible change, an added field, passes, so the contract does not block legitimate evolution. Test the consumer against a stub that omits a relied-on field and assert the consumer test fails, proving the stub is derived from the contract.

# provider verification fails when a consumer-read field is removed
# change the provider to drop order.total, run the verification, and assert it fails
node verify-provider.mjs   # must exit non-zero and name the broken contract

Common pitfalls

Pinning every provider field so nothing can change, a hand-written consumer mock that drifts from the real provider, running contract verification outside the provider’s pipeline so it is not enforced, no contract version so a breaking change has no migration path, and keeping a contract from a consumer that no longer exists are the recurring mistakes. Contracts over relied-on fields, derived stubs, provider-pipeline verification, versioned contracts, and attribution address them.

Conclusion

A contract test checks the agreement between services directly. Define the contract from what consumers rely on, verify the provider against it in its pipeline, stub the provider from the same contract for the consumer, and version the contract with the API. Self-check by removing a relied-on field and asserting the provider verification fails, and by adding a field and asserting it still passes. Then a change that would break a consumer fails in the provider’s build, not in production.

Sources: Pact: Contract testing, Martin Fowler: Contract tests, Consumer-driven contracts (Wikipedia).

FAQ

How is a contract test different from an integration test?
An integration test runs both services together. A contract test runs each against the agreed contract separately: the provider is checked to satisfy it, and the consumer against a stub from it. It catches a mismatch without standing up the whole system.
What belongs in the contract?
What the consumer actually relies on: the fields it reads, their types, the status codes it branches on, and the error shape it handles. Not every field the provider returns, only the ones a consumer depends on, so the contract stays focused.

Related Examples