Contract Testing with Pact

VerifiedSafe

Implement consumer-driven contract testing with Pact, including provider verification and Pact Broker integration.

Sby Skills Guide Bot
DevelopmentIntermediate
9/6/2026
Claude CodeCursorWindsurfCopilotCodex
#contract-testing#microservices#consumer-driven#api-testing#pact-broker

Recommended for

Automated summary

Guides implementation of consumer-driven contract testing with Pact, from writing consumer tests to provider verification, including Broker sharing and the can-i-deploy workflow.

Strengths

  • Gives concrete TypeScript examples for both consumer tests and provider verification.
  • Shows provider state handlers and error cases such as 404 responses.
  • Connects contract tests to a CI/CD flow via Broker sharing and can-i-deploy.

Limitations

  • Detailed examples focus on JavaScript/TypeScript, while other languages are only mentioned.
  • Assumes prior familiarity with Pact, a Broker, and CI/CD pipelines.
  • Provides limited guidance on debugging verification failures or choosing matchers.
When to use it

Use it when introducing or standardizing contract testing between services and automating validation in CI.

When not to use it

Avoid it when you only need to mock an API for isolated tests without shared consumer-provider contracts.

Security analysis

Safe
Quality score84/100

This is instructional documentation for Pact contract testing. It contains only declarative test code, CI YAML, and shell snippets invoking the official pact-broker CLI. No destructive commands, no obfuscated payloads, no exfiltration; tokens are referenced via environment variables and GitHub secrets, which is standard practice. No prompt-injection attempts were present.

No concerns found

How this analysis is made

Examples

Consumer test for user lookup
Write a Pact consumer test in TypeScript for order-service calling user-service GET /api/users/1, with a 200 response containing id, name, and email, plus a 404 case.
Provider verification with state handlers
Set up Pact provider verification for user-service against order-service's pact file, including a state handler for 'a user with ID 1 exists' that seeds the database.
Can-i-deploy in CI
Show how to add Pact Broker can-i-deploy checks to our order-service CI pipeline before deployment.

name: pact description: When the user wants to implement consumer-driven contract testing between microservices using Pact. Also use when the user mentions "pact," "contract testing," "consumer-driven contracts," "CDC testing," "provider verification," or "Pact Broker." For API mocking, see mockoon or wiremock. metadata: author: terminal-skills version: "1.0.0" category: development tags: - contract-testing - microservices - consumer-driven - api-testing

Pact

Overview

You are an expert in Pact, the consumer-driven contract testing framework. You help users write consumer tests that generate pact files, set up provider verification, configure a Pact Broker for sharing contracts, and integrate the "can-i-deploy" workflow into CI/CD pipelines. You understand the contract testing philosophy: consumers define what they need, providers verify they can deliver.

Instructions

Initial Assessment

  1. Architecture — Which services need contract testing?
  2. Language — JavaScript, Java, Python, Go, or .NET?
  3. Broker — Self-hosted Pact Broker or Pactflow (SaaS)?
  4. CI — How are services deployed? Independent pipelines?

Consumer Test (JavaScript)

// tests/consumer.pact.test.ts — Consumer-side Pact test.
// Defines what the consumer expects from the user-service API.
import { PactV3, MatchersV3 } from '@pact-foundation/pact';
import { resolve } from 'path';
import { UserApiClient } from '../src/api/userClient';

const { like, eachLike, string, integer } = MatchersV3;

const provider = new PactV3({
  consumer: 'order-service',
  provider: 'user-service',
  dir: resolve(__dirname, '../pacts'),
});

describe('User API - Consumer Tests', () => {
  it('should return user by ID', async () => {
    await provider
      .given('a user with ID 1 exists')
      .uponReceiving('a request for user 1')
      .withRequest({
        method: 'GET',
        path: '/api/users/1',
        headers: { Accept: 'application/json' },
      })
      .willRespondWith({
        status: 200,
        headers: { 'Content-Type': 'application/json' },
        body: like({
          id: integer(1),
          name: string('Jane Doe'),
          email: string('jane@example.com'),
        }),
      })
      .executeTest(async (mockServer) => {
        const client = new UserApiClient(mockServer.url);
        const user = await client.getUser(1);
        expect(user.id).toBe(1);
        expect(user.name).toBeDefined();
        expect(user.email).toBeDefined();
      });
  });

  it('should return 404 for non-existent user', async () => {
    await provider
      .given('no user with ID 999 exists')
      .uponReceiving('a request for non-existent user')
      .withRequest({
        method: 'GET',
        path: '/api/users/999',
      })
      .willRespondWith({
        status: 404,
        body: like({ error: string('User not found') }),
      })
      .executeTest(async (mockServer) => {
        const client = new UserApiClient(mockServer.url);
        await expect(client.getUser(999)).rejects.toThrow('User not found');
      });
  });
});

Provider Verification

// tests/provider.pact.test.ts — Provider-side verification test.
// Verifies that user-service fulfills the contracts from all consumers.
import { Verifier } from '@pact-foundation/pact';
import { resolve } from 'path';
import { startApp } from '../src/app';

describe('User Service - Provider Verification', () => {
  let server: any;

  beforeAll(async () => {
    server = await startApp(3456);
  });

  afterAll(async () => {
    await server.close();
  });

  it('should fulfill all consumer contracts', async () => {
    const verifier = new Verifier({
      providerBaseUrl: 'http://localhost:3456',
      provider: 'user-service',
      pactUrls: [resolve(__dirname, '../pacts/order-service-user-service.json')],
      stateHandlers: {
        'a user with ID 1 exists': async () => {
          await seedDatabase({ id: 1, name: 'Jane Doe', email: 'jane@example.com' });
        },
        'no user with ID 999 exists': async () => {
          await clearDatabase();
        },
      },
    });

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

Pact Broker Integration

// tests/provider-broker.pact.test.ts — Provider verification against Pact Broker.
// Fetches contracts from the broker instead of local files.
import { Verifier } from '@pact-foundation/pact';

const verifier = new Verifier({
  providerBaseUrl: 'http://localhost:3456',
  provider: 'user-service',
  pactBrokerUrl: process.env.PACT_BROKER_BASE_URL,
  pactBrokerToken: process.env.PACT_BROKER_TOKEN,
  publishVerificationResult: process.env.CI === 'true',
  providerVersion: process.env.GIT_COMMIT,
  providerVersionBranch: process.env.GIT_BRANCH,
  consumerVersionSelectors: [
    { mainBranch: true },
    { deployedOrReleased: true },
  ],
});

Can-I-Deploy

# can-i-deploy.sh — Check if it's safe to deploy a service.
# Queries the Pact Broker to verify all contracts are satisfied.

# Check if consumer can deploy
npx pact-broker can-i-deploy \
  --pacticipant order-service \
  --version $(git rev-parse HEAD) \
  --to-environment production \
  --broker-base-url $PACT_BROKER_BASE_URL \
  --broker-token $PACT_BROKER_TOKEN

# Record deployment
npx pact-broker record-deployment \
  --pacticipant order-service \
  --version $(git rev-parse HEAD) \
  --environment production \
  --broker-base-url $PACT_BROKER_BASE_URL \
  --broker-token $PACT_BROKER_TOKEN

CI Integration

# .github/workflows/pact-consumer.yml — Consumer contract test pipeline.
# Runs consumer tests, publishes pacts to broker, checks can-i-deploy.
name: Consumer Contract Tests
on: [push]
jobs:
  pact:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npm test -- --testPathPattern=pact
      - name: Publish pacts
        run: |
          npx pact-broker publish pacts/ \
            --consumer-app-version ${{ github.sha }} \
            --branch ${{ github.ref_name }} \
            --broker-base-url ${{ secrets.PACT_BROKER_URL }} \
            --broker-token ${{ secrets.PACT_BROKER_TOKEN }}
      - name: Can I deploy?
        run: |
          npx pact-broker can-i-deploy \
            --pacticipant order-service \
            --version ${{ github.sha }} \
            --to-environment production \
            --broker-base-url ${{ secrets.PACT_BROKER_URL }} \
            --broker-token ${{ secrets.PACT_BROKER_TOKEN }}

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/contract-testing-with-pact-mtpag6tp/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/contract-testing-with-pact-mtpag6tp' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/contract-testing-with-pact-mtpag6tp/download' --output '.skill-downloads/contract-testing-with-pact-mtpag6tp/SKILL.md.part' && mv '.skill-downloads/contract-testing-with-pact-mtpag6tp/SKILL.md.part' '.skill-downloads/contract-testing-with-pact-mtpag6tp/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/contract-testing-with-pact-mtpag6tp/SKILL.md' && test -s '.skill-downloads/contract-testing-with-pact-mtpag6tp/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/pact' && cp -R '.skill-downloads/contract-testing-with-pact-mtpag6tp' '.claude/skills/pact'

Cursor
test -f '.skill-downloads/contract-testing-with-pact-mtpag6tp/SKILL.md' && test -s '.skill-downloads/contract-testing-with-pact-mtpag6tp/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/pact' && cp -R '.skill-downloads/contract-testing-with-pact-mtpag6tp' '.cursor/skills/pact'

Codex
test -f '.skill-downloads/contract-testing-with-pact-mtpag6tp/SKILL.md' && test -s '.skill-downloads/contract-testing-with-pact-mtpag6tp/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/pact' && cp -R '.skill-downloads/contract-testing-with-pact-mtpag6tp' '.agents/skills/pact'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/contract-testing-with-pact-mtpag6tp'

openskills read 'contract-testing-with-pact-mtpag6tp'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/contract-testing-with-pact-mtpag6tp/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills