How-To Guide

How to Implement Contract Testing with Pact

Replace brittle integration tests with contract tests between consumers and providers, using consumer-driven pacts and a broker.

On this page

  1. Introduction
  2. What a Contract Test Is
  3. Writing the Consumer Side
  4. Matchers Over Exact Values
  5. Verifying on the Provider Side
  6. The Broker and the Deploy Gate
  7. What Contract Testing Does Not Cover
  8. Common Pitfalls and Conclusion

Introduction

End-to-end integration tests are slow, flaky and coupled to every service being up at once, yet they are the only way many teams verify that service A and service B still agree on their API. Contract testing extracts that agreement into an artifact both sides can verify independently. The consumer records what it expects from the provider as a pact; the provider verifies it can satisfy the pact. Each side tests against the contract, not against the other service, so the tests are fast, isolated and still catch the integration bug before deploy.

What a Contract Test Is

A contract test captures an agreement between a consumer and a provider, typically as a set of request and response examples. The consumer generates a pact by running its code against a mock: it makes a request, and the mock records the request and the response the consumer expects. The provider then replays those requests against its real implementation and verifies the responses match.

The artifact is the contract, and it is versioned and shared. Neither side calls the other over the network during its own test, so both run in isolation and fast. The integration bug is caught by the mismatch between the consumer’s expectation and the provider’s actual response, which is exactly the disagreement that end-to-end tests would have caught more slowly.

# consumer-driven contract flow
consumer test -> defines expected request/response -> writes a PACT file(JSON)
pact published -> pact broker
provider test -> replays requests from the pact against real code
              -> verifies responses match -> records verification result
ci gate: can deploy provider? = all consumer pacts verified
        can deploy consumer? = its provider can satisfy its pact

Writing the Consumer Side

The consumer test starts a mock provider, configures the interaction it expects, exercises its own client code against the mock, and asserts the result. The mock records the interaction into the pact. The test verifies the consumer’s handling of the response, not the provider, which keeps it fast and independent.

Keep interactions minimal and specific: one interaction per scenario, with the exact request the consumer makes and the minimal response it needs. A consumer that expects a large response with fields it does not use creates a brittle contract; expect only what you consume, so the provider is free to add fields without breaking you.

import { PactV3, MatchersV3 } from '@pact-foundation/pact';

const provider = new PactV3({ consumer: 'orders-web', provider: 'orders-api' });

test('get order by id', async () => {
  provider
    .given('an order exists')
    .uponReceiving('a request for order 42')
    .withRequest({ method: 'GET', path: '/orders/42' })
    .willRespondWith({
      status: 200,
      body: {
        id: '42',
        status: MatchersV3.string('paid'),   // match type, not exact value
      },
    });

  await provider.executeTest(async (mock) => {
    const client = new OrdersClient(mock.url);
    const order = await client.getOrder('42');
    expect(order.status).toBe('paid');
  });
});

Matchers Over Exact Values

A contract that asserts exact values breaks whenever the data changes. Use matchers to describe the shape: a string equals a string, a number is an integer, a field matches a regex. The pact then verifies the structure the consumer depends on, not the specific values, so a provider can change data without breaking the contract.

Match types and formats, and assert exact values only where the consumer genuinely depends on them, such as an enum’s allowed values or a status code. Over-matched contracts are brittle; under-matched contracts miss real breakages. The guide is: match what the consumer’s code needs, and no more.

body: {
  id: MatchersV3.like('a1b2'),                 // string of any value
  total: MatchersV3.integer(1999),             // any integer
  currency: MatchersV3.regex(/^[A-Z]{3}$/, 'USD'), // ISO currency code
  status: MatchersV3.string('paid'),           // any string (or enum values)
  items: MatchersV3.eachLike({ sku: 'X', qty: 1 }), // array of that shape
}

Verifying on the Provider Side

The provider fetches the pacts and replays each request against its real implementation, checking that the response matches. Provider states let the pact specify the setup, such as “an order exists”, and the provider supplies that state before each interaction. The verification finishes by recording the result back to the broker, so the consumer knows its contract is satisfied.

Verification must run against the real provider code, not a mock, or it proves nothing. Run it in the provider’s CI; a failed verification means a change would break a consumer, and the provider must not deploy until it is resolved, by fixing the code or by coordinating the consumer’s change.

import { Verifier } from '@pact-foundation/pact';

const opts = {
  provider: 'orders-api',
  providerBaseUrl: 'http://localhost:3001',
  pactBrokerUrl: process.env.PACT_BROKER_URL,
  publishVerificationResult: true,
  providerVersion: process.env.GIT_SHA,
  stateHandlers: {
    'an order exists': async () => { await seedOrder('42'); },   // real setup
  },
};

new Verifier(opts).verifyProvider().then(() => console.log('verified'));

The Broker and the Deploy Gate

A pact broker stores pacts and verification results, and adds the crucial capability: can-i-deploy. Before deploying, a service asks the broker whether its version is compatible with the versions of its counterparts that are currently deployed. The answer is a gate: deploy only when every relevant contract is verified for this version.

This is what turns contract testing from a nice test into a deployment safety mechanism. It catches the case where the consumer is fine against every provider version except the one now in production, and the reverse. The broker records which pact versions were verified by which provider versions, so the gate is a lookup rather than a guess.

# before deploying, ask the broker if this version is safe
pact-broker can-i-deploy \
  --pacticipant orders-api --version "$GIT_SHA" \
  --to-environment production
# exits 0 => safe to deploy; non-zero => a consumer contract is unsatisfied
# after deploy: record the deployment so future gates see this version

What Contract Testing Does Not Cover

Contract tests verify the request and response shapes each consumer depends on. They do not test the provider’s internal logic, performance, or the behaviour of flows spanning many services. Those remain the job of provider unit and integration tests and, sparingly, end-to-end tests for the most critical user journeys.

They also do not catch a provider that satisfies every individual contract but behaves badly under combined load. Keep contract testing as one layer in a test strategy: fast provider tests, consumer-driven contracts for integration, and a small number of end-to-end tests for the critical paths. Replacing end-to-end tests entirely usually means losing coverage of cross-service behaviour.

# test pyramid with contracts
provider unit/integration   logic, edge cases        (many, fast)
contract tests              consumer<->provider shape (per pair, fast)
end-to-end                  critical user journeys   (few, slow)
# contracts replace most service-to-service integration tests,
# not provider logic tests nor critical-path E2E

Common Pitfalls and Conclusion

Do not assert exact values where a matcher would do. Do not verify the provider against a mock. Do not skip the deploy gate, or the contracts are documentation rather than a safety mechanism. Do not let pacts accumulate stale consumers that no longer exist. And do not adopt contract testing expecting it to replace provider unit tests or critical end-to-end journeys.

Contract testing makes the agreement between a consumer and a provider an explicit, testable artifact. The consumer writes a pact with matchers describing the shape it needs, the provider verifies it against real code, the broker gates deploys on verification, and both sides test in isolation. The result is integration safety that is fast, isolated and caught before deploy rather than in a flaky end-to-end suite.

Sources: Pact: Contract testing, Pact: Matching, Pact Broker: can-i-deploy.

FAQ

Does contract testing replace end-to-end tests?
Most service-to-service integration tests, yes, because it catches the request/response disagreements they were verifying, but faster and in isolation. It does not replace provider logic tests or the few end-to-end tests for critical user journeys spanning many services.
Why use matchers instead of exact values?
Exact values make the contract break whenever data changes. Matchers describe the shape the consumer depends on (a string, an integer, a regex), so the provider can change values without breaking the contract, while still catching a missing field or a changed type.

Related Examples