Contract Testing TypeScript Microservices with Pact

Contract Testing TypeScript Microservices with Pact

When TypeScript microservices communicate over HTTP or message queues, integration tests that rely on real deployed services are slow, flaky, and hard to maintain. Contract testing with Pact gives you a fast, isolated alternative: consumers define what they expect from providers, providers verify they still meet those expectations. This guide covers writing consumer contracts in TypeScript, verifying them on the provider side, and running Pact in CI with a Pact Broker.

Key Takeaways

Consumer-driven contracts prevent breaking changes silently. The consumer defines what shape of response it needs. The provider proves it can deliver that shape. If the provider breaks the contract, CI fails — before deployment.

Pact tests are not end-to-end tests. Pact tests run locally against mock servers and stubs. They verify the interface contract, not business logic.

Use PactV3 for TypeScript projects. The V3 API has better TypeScript types, native async/await support, and aligns with Pact Specification V3/V4.

Pact Broker is the source of truth for contracts. Consumer publishes pacts; provider fetches and verifies. Neither side needs the other deployed.

Match loosely, not literally. Use like(), eachLike(), and regex matchers instead of exact values. Contracts should verify shape, not data.

Why Contract Testing?

In a microservices architecture, the hardest problem isn't writing services — it's knowing when one service breaks another. Integration tests that deploy everything and fire real HTTP requests catch these breaks, but they're slow (minutes to spin up), fragile (race conditions, network flakiness), and expensive to maintain.

Contract testing takes a different approach:

  1. Consumer writes a contract: "I call GET /users/{id} and expect { id: string, name: string, email: string }"
  2. Pact generates a pact file from that contract
  3. Provider runs against the pact file and proves it can satisfy the contract
  4. Neither side needs the other deployed — they communicate through the pact file

The result is fast (seconds per test), reliable (no network), and catches breaking API changes before they ship.

Project Setup

Install Pact for both consumer and provider:

npm install --save-dev @pact-foundation/pact

For the Pact Broker client (publishing and fetching contracts):

npm install --save-dev @pact-foundation/pact-broker-client

Consumer Contract Test

The consumer writes a test that defines the HTTP interactions it expects. Pact runs a mock server that records these expectations as a pact file.

// consumer/src/users.client.ts
export interface UserDTO {
  id: string;
  name: string;
  email: string;
  role: 'admin' | 'viewer' | 'editor';
}

export async function getUser(userId: string): Promise<UserDTO> {
  const response = await fetch(`${process.env.USER_SERVICE_URL}/users/${userId}`);
  
  if (!response.ok) {
    throw new Error(`User service error: ${response.status}`);
  }
  
  return response.json() as Promise<UserDTO>;
}

export async function createUser(
  data: Pick<UserDTO, 'name' | 'email' | 'role'>
): Promise<UserDTO> {
  const response = await fetch(`${process.env.USER_SERVICE_URL}/users`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });

  if (!response.ok) {
    throw new Error(`User service error: ${response.status}`);
  }

  return response.json() as Promise<UserDTO>;
}
// consumer/src/users.client.pact.test.ts
import { PactV3, MatchersV3 } from '@pact-foundation/pact';
import path from 'path';
import { getUser, createUser } from './users.client';

const { like, regex, eachLike } = MatchersV3;

const provider = new PactV3({
  consumer: 'BillingService',
  provider: 'UserService',
  dir: path.resolve(__dirname, '../../pacts'),
  logLevel: 'warn',
});

describe('UserService client contract', () => {
  describe('GET /users/:id', () => {
    test('returns user when found', async () => {
      await provider.addInteraction({
        states: [{ description: 'user with ID abc123 exists' }],
        uponReceiving: 'a request for user abc123',
        withRequest: {
          method: 'GET',
          path: '/users/abc123',
        },
        willRespondWith: {
          status: 200,
          headers: { 'Content-Type': 'application/json' },
          body: like({
            id: 'abc123',
            name: 'Alice Johnson',
            email: regex('\\S+@\\S+\\.\\S+', 'alice@example.com'),
            role: 'viewer',
          }),
        },
      });

      await provider.executeTest(async (mockServer) => {
        process.env.USER_SERVICE_URL = mockServer.url;
        const user = await getUser('abc123');

        expect(user.id).toBe('abc123');
        expect(user.name).toBeDefined();
        expect(user.email).toMatch(/@/);
      });
    });

    test('returns 404 when user not found', async () => {
      await provider.addInteraction({
        states: [{ description: 'user with ID missing does not exist' }],
        uponReceiving: 'a request for a non-existent user',
        withRequest: {
          method: 'GET',
          path: '/users/missing',
        },
        willRespondWith: {
          status: 404,
          body: like({ error: 'User not found' }),
        },
      });

      await provider.executeTest(async (mockServer) => {
        process.env.USER_SERVICE_URL = mockServer.url;
        await expect(getUser('missing')).rejects.toThrow('User service error: 404');
      });
    });
  });

  describe('POST /users', () => {
    test('creates a new user', async () => {
      await provider.addInteraction({
        states: [],
        uponReceiving: 'a request to create a user',
        withRequest: {
          method: 'POST',
          path: '/users',
          headers: { 'Content-Type': 'application/json' },
          body: like({
            name: 'Bob Smith',
            email: 'bob@example.com',
            role: 'editor',
          }),
        },
        willRespondWith: {
          status: 201,
          headers: { 'Content-Type': 'application/json' },
          body: like({
            id: regex('[a-z0-9-]+', 'new-user-id'),
            name: 'Bob Smith',
            email: 'bob@example.com',
            role: 'editor',
          }),
        },
      });

      await provider.executeTest(async (mockServer) => {
        process.env.USER_SERVICE_URL = mockServer.url;
        const user = await createUser({
          name: 'Bob Smith',
          email: 'bob@example.com',
          role: 'editor',
        });

        expect(user.id).toBeDefined();
        expect(user.name).toBe('Bob Smith');
      });
    });
  });
});

Running this test generates a pact file at pacts/BillingService-UserService.json. This file is the contract.

Understanding Matchers

Never use exact values in contracts. The consumer doesn't care that the user's name is "Alice Johnson" — it cares that a name field exists and is a string. Matchers express that:

Matcher Use when
like(value) You care about shape and type, not exact value
eachLike(item) Array must contain at least one item of this shape
regex(pattern, example) Field must match a pattern (email, UUID, date)
integer() Field must be an integer
decimal() Field must be a decimal number
boolean() Field must be a boolean
timestamp(format) Field must be a timestamp in the specified format
// Too strict — breaks if test data changes
body: {
  id: 'abc123',
  email: 'alice@example.com',
  createdAt: '2026-01-15T10:30:00Z',
}

// Correct — validates shape, not values
body: like({
  id: regex('[a-z0-9-]+', 'abc123'),
  email: regex('[^@]+@[^@]+', 'alice@example.com'),
  createdAt: regex('\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z', '2026-01-15T10:30:00Z'),
})

Provider Verification

The provider runs the contract against its real implementation. For each interaction in the pact file, Pact replays the request and verifies the response matches.

// provider/src/pact.verification.test.ts
import { Verifier } from '@pact-foundation/pact';
import path from 'path';
import { app } from './app';
import { db } from './db';

describe('Provider verification against BillingService', () => {
  let server: ReturnType<typeof app.listen>;
  let serverPort: number;

  beforeAll(async () => {
    // Seed test database
    await db.migrate.latest();
    
    // Start the real provider app
    await new Promise<void>((resolve) => {
      server = app.listen(0, () => {
        serverPort = (server.address() as { port: number }).port;
        resolve();
      });
    });
  });

  afterAll(async () => {
    await new Promise((resolve) => server.close(resolve));
    await db.migrate.rollback();
  });

  it('validates consumer contracts', async () => {
    const verifier = new Verifier({
      provider: 'UserService',
      providerBaseUrl: `http://localhost:${serverPort}`,

      // Load pacts from local file (dev) or Pact Broker (CI)
      pactUrls: [
        path.resolve(__dirname, '../../pacts/BillingService-UserService.json'),
      ],

      // State handlers set up database state for each test
      stateHandlers: {
        'user with ID abc123 exists': async () => {
          await db('users').insert({
            id: 'abc123',
            name: 'Alice Johnson',
            email: 'alice@example.com',
            role: 'viewer',
          });
        },
        'user with ID missing does not exist': async () => {
          await db('users').where({ id: 'missing' }).delete();
        },
      },

      logLevel: 'warn',
    });

    await verifier.verifyProvider();
  });
});

State handlers run before each interaction to set up the required database state. They're the bridge between "what the consumer assumed" and "what the provider actually has in its database."

Pact Broker Integration

Local pact files work for a single team. For multiple teams or CI/CD, use a Pact Broker:

// consumer: publish pacts after tests pass
// package.json
{
  "scripts": {
    "test:pact": "jest pact.test.ts",
    "publish:pacts": "pact-broker publish ./pacts --consumer-app-version $GITHUB_SHA --tag $BRANCH_NAME"
  }
}
// provider: fetch pacts from broker instead of local files
const verifier = new Verifier({
  provider: 'UserService',
  providerBaseUrl: `http://localhost:${serverPort}`,
  
  // Fetch from broker instead of local file
  pactBrokerUrl: process.env.PACT_BROKER_URL,
  pactBrokerToken: process.env.PACT_BROKER_TOKEN,
  
  // Verify against consumers that are deployed to production
  consumerVersionSelectors: [
    { mainBranch: true },
    { deployedOrReleased: true },
  ],
  
  publishVerificationResult: true,
  providerVersion: process.env.GITHUB_SHA,
  
  stateHandlers: { /* ... */ },
});

With a broker, neither team needs the other's code. The consumer publishes its pact file. The provider fetches and verifies. The broker records which versions are compatible.

Can-I-Deploy

The Pact Broker provides a can-i-deploy CLI check that tells you whether a specific version of a service is compatible with all its consumers:

# Before deploying UserService v2.3.1 to production
npx pact-broker can-i-deploy \
  --pacticipant UserService \
  --version 2.3.1 \
  --to-environment production

This prevents breaking changes from reaching production — if any consumer has a failing contract verification against the new version, can-i-deploy fails and the deployment is blocked.

CI/CD Pipeline

# .github/workflows/pact.yml

# Consumer job: run pact tests and publish
consumer-pacts:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v4
    - run: npm ci
    - run: npm run test:pact
    - run: |
        npx pact-broker publish ./pacts \
          --consumer-app-version ${{ github.sha }} \
          --tag ${{ github.ref_name }} \
          --broker-base-url ${{ secrets.PACT_BROKER_URL }} \
          --broker-token ${{ secrets.PACT_BROKER_TOKEN }}

# Provider job: verify contracts
provider-verification:
  runs-on: ubuntu-latest
  needs: consumer-pacts  # Ensure latest pacts are published first
  steps:
    - uses: actions/checkout@v4
    - run: npm ci
    - run: npm run test:pact:verify
      env:
        PACT_BROKER_URL: ${{ secrets.PACT_BROKER_URL }}
        PACT_BROKER_TOKEN: ${{ secrets.PACT_BROKER_TOKEN }}
        GITHUB_SHA: ${{ github.sha }}

# Deployment gate
deploy-gate:
  runs-on: ubuntu-latest
  needs: provider-verification
  steps:
    - run: |
        npx pact-broker can-i-deploy \
          --pacticipant UserService \
          --version ${{ github.sha }} \
          --to-environment production \
          --broker-base-url ${{ secrets.PACT_BROKER_URL }} \
          --broker-token ${{ secrets.PACT_BROKER_TOKEN }}

Message Contract Testing

Pact also supports message-based contracts (Kafka, RabbitMQ, SNS). The consumer defines what message structure it expects:

// Consumer: defines the message it can handle
const messagePact = new PactV3({
  consumer: 'OrderProcessor',
  provider: 'UserEvents',
  dir: path.resolve(__dirname, '../../pacts'),
});

test('handles UserCreated event', async () => {
  await messagePact.addSynchronousInteractions({
    description: 'a UserCreated event',
    withRequest: {
      method: 'GET',
      path: '/ignored', // Not used for message contracts
    },
    willRespondWith: {
      status: 200,
      contentType: 'application/json',
      body: like({
        eventType: 'UserCreated',
        userId: regex('[a-z0-9-]+', 'user-123'),
        email: regex('[^@]+@[^@]+', 'user@example.com'),
        createdAt: like('2026-01-01T00:00:00Z'),
      }),
    },
  });
});

Common Mistakes

Testing too much in contracts. Contracts verify interface compatibility, not business logic. "Creating a user increments the user count" is not a contract test — it's an integration test.

Using exact values in matchers. like('Alice') tests that a string exists. 'Alice' tests that the string is exactly 'Alice'. Use matchers.

Not writing state handlers. Without state handlers, provider verification runs against an empty database and returns 404 for every interaction. Every interaction needs a corresponding state.

Publishing pacts without version tagging. Tag pacts with branch name and commit SHA. Without tags, can-i-deploy can't determine which pact corresponds to which deployment environment.

Skipping can-i-deploy in the deployment pipeline. The whole point of Pact Broker is to gate deployments on contract compatibility. If you don't run can-i-deploy before deploying, you're back to hoping nothing breaks.

Contract testing with Pact is infrastructure overhead upfront — setting up the broker, writing state handlers, wiring CI. But once it's running, it gives you something no integration test suite can: a guarantee that service-to-service interfaces are compatible without both services deployed at the same time.

Read more

Start now free