Email copiado — support@tuurt.com
Cargando experiencia
testing · November 04, 2026 · 7 min

Contract Testing with Pact: Why a Local Mock Won't Save You From Breaking the Consumer

A local mock only proves your consumer understands the payload you made up yourself. We go over how Pact flips that with consumer-driven contracts, the Pact Broker, and the can-i-deploy gate that blocks a deploy that would break the consumer.

By Tuurt Team

Contract testing with Pact: why a local mock won't save you from breaking the consumer

When a service calls another one over HTTP or messaging, the most common way to test that relationship is to mock the external service's response inside the consumer's unit tests. You build an object that mimics the expected payload, verify the consumer's code handles it correctly, and the test passes. It's fast, it doesn't depend on infrastructure, and it never fails because of another team's work. It also proves almost nothing about whether that mock still reflects reality.

The mock describes what the consumer expects to receive, not what the provider actually sends today. If the team that owns the provider renames a field, makes it optional, changes a data type, or reorders an enum, that change doesn't touch a single consumer test. The mock stays exactly the same hardcoded object it was before the change, because nobody updated it, and there's no mechanism that tells anyone the mock stopped matching reality. The problem surfaces in production, when the consumer gets a real response that doesn't match what it expected, and by then the deploy that broke the contract shipped days ago.

What a local mock actually proves

A local mock proves exactly one thing: that the consumer's code correctly handles a payload with that specific shape. It doesn't prove the provider actually produces payloads with that shape, or that it will keep doing so after the next change.

That isolation isn't a flaw in the mock, it's exactly what it's for: isolating the unit under test from its external dependencies so you can test its logic without spinning up someone else's infrastructure. The mistake isn't using mocks, it's assuming a mock that's never compared against the provider's real behavior can stand in for an integration test that actually does that comparison.

Consumer-driven contract testing

Pact flips the usual order of this relationship. Instead of the provider defining a contract and the consumer adapting to it, the consumer writes a test that expresses exactly what it expects for the cases it actually uses, and Pact generates a contract file (the "pact") in JSON from that test. That file isn't a guess about the provider: it's an executable specification of the minimal interaction the consumer needs.

A Pact consumer test in Node looks like this:

const { PactV3, MatchersV3 } = require('@pact-foundation/pact');
const { like, eachLike } = MatchersV3;

const provider = new PactV3({
  consumer: 'order-service',
  provider: 'inventory-service',
});

describe('inventory client', () => {
  it('returns available stock for a product', () => {
    provider
      .given('product sku-123 has stock')
      .uponReceiving('a stock query')
      .withRequest({
        method: 'GET',
        path: '/stock/sku-123',
      })
      .willRespondWith({
        status: 200,
        body: {
          sku: like('sku-123'),
          available: like(42),
          variants: eachLike({ color: like('black') }),
        },
      });

    return provider.executeTest(async (mockServer) => {
      const client = new InventoryClient(mockServer.url);
      const result = await client.getStock('sku-123');
      expect(result.available).toBeGreaterThanOrEqual(0);
    });
  });
});

The difference from a plain mock is in the matchers (like, eachLike). Instead of pinning the exact value 42, like(42) declares the field must exist and be a number, regardless of the concrete value. That's deliberate: the contract shouldn't depend on specific data the provider can legitimately change, only on the shape and type of the response the consumer needs to function.

Running this test does two things: Pact verifies the consumer's code against a mock server it builds automatically from the definition, and it writes the contract file with the full interaction, ready to be published.

The Pact Broker's role

A contract generated by the consumer is useless sitting in its own repository. Pact Broker is the component that receives those published contracts and makes them available to the provider, and that also records verification results in the other direction.

The flow has two independent halves:

  1. The consumer's pipeline runs its Pact tests and publishes the resulting contract to the Broker, tied to a specific consumer version (usually the commit hash).
  2. The provider's pipeline pulls the relevant contracts from the Broker, replays them against a real (or as-real-as-possible) instance of the provider, confirms each expected interaction actually responds the way the contract says, and publishes that verification result back to the Broker.
const { Verifier } = require('@pact-foundation/pact');

new Verifier({
  provider: 'inventory-service',
  providerBaseUrl: 'http://localhost:4000',
  pactBrokerUrl: 'https://pact-broker.tuurt.internal',
  publishVerificationResult: true,
  providerVersion: process.env.GIT_COMMIT,
  consumerVersionSelectors: [{ mainBranch: true }, { deployedOrReleased: true }],
}).verifyProvider();

consumerVersionSelectors is the part that keeps you from verifying against stale contracts: instead of pulling every contract ever published, it pulls only the main branch of each consumer plus whatever is actually deployed somewhere, which is what you really can't afford to break.

The CI gate: can-i-deploy

The piece that turns this from "useful information" into "a mechanism that actually prevents the incident" is the can-i-deploy command, run before authorizing a deploy:

pact-broker can-i-deploy \
  --pacticipant inventory-service \
  --version $GIT_COMMIT \
  --to-environment production

This command asks the Broker: for the version I'm about to deploy, is there at least one successful verification against every consumer that depends on this service in that environment? If any consumer deployed in production has a contract this provider version didn't verify, or verified and failed, the command returns a non-zero exit code and the pipeline blocks the deploy before the change reaches production. It's not an alert someone can ignore: it's a real gate in the pipeline, with the same authority as any other required check.

That's exactly the problem a local mock couldn't solve: now the provider change that breaks the contract gets caught in the provider's own pipeline, before the deploy, instead of surfacing as a production incident days later.

What didn't work on the first try

The first thing we tried was writing contracts by hand, as plain JSON files checked into the consumer's repository, skipping Pact's tests entirely. The idea was to skip the library's learning curve and just document the contract we believed we needed.

It didn't work, for a reason that's obvious in hindsight: a hand-written contract is never validated against the consumer's actual code. Nothing guaranteed the consumer really made those calls in that format, or that its logic actually tolerated the variations the contract claimed to allow. We ended up with contracts describing an aspirational interaction, not the one the consumer's code really executed, which is exactly the same problem as a stale mock, just with an extra layer of false confidence because "now we have contracts." What worked was always generating the contract from an executable test against a real mock server, never written by hand, so the contract couldn't drift from what the consumer actually does.

What Pact doesn't replace

Contract testing doesn't replace end-to-end integration tests. Pact verifies the provider meets the shape and behavior the consumer expects for the specific interactions that consumer exercises in its tests, interaction by interaction. It doesn't verify the whole system's behavior under real load, it doesn't verify latency, it doesn't verify what happens once two more services beyond the direct provider enter the chain, and it doesn't replace a staging environment where you can watch the full business flow end to end with real data. If a consumer never writes a test exercising a given use case, that case simply isn't in the contract, and Pact has no way to know it's missing.

What we check before calling a Pact integration done

Before considering contract testing between two services finished, we confirm the consumer's pipeline actually publishes the pact to the Broker on every main-branch build, not just generates it locally. We check that can-i-deploy runs as a required step on both sides, consumer and provider, not as an informational check someone can skip. And we verify the provider's consumerVersionSelectors point to versions that are actually deployed, not just any contract ever published, because verifying against a contract from a branch that never reached production prevents no real incident.

pact microservices ci-cd testing
← Back to blog