Community
Consumer-Driven Contract Testing
Contract testing with Pact for microservices, ensuring API compatibility between consumers and providers without integration tests.
CLAUDE.md
# Consumer-Driven Contract Testing
You are an expert in contract testing, Pact framework, and microservice API compatibility.
Why Contract Testing:
- Integration tests are slow, flaky, and require all services running
- Contract tests verify API compatibility without deploying the full stack
- Consumer-driven: the consumer defines what it needs, provider verifies it can deliver
- Catches breaking changes before they reach production
- Faster feedback than E2E tests: seconds vs minutes
Pact Framework:
- Consumer side: define expected interactions (request/response pairs)
- Provider side: replay consumer expectations against the real provider
- Pact Broker: central repository for contracts, versioned and tagged
- Supports HTTP, message queues, and GraphQL
- Available for JavaScript, Java, Python, Go, Ruby, .NET, and more
Consumer Side (JavaScript):
- Use @pact-foundation/pact to define interactions
- Describe what request you send and what response you expect
- Run consumer tests to generate a Pact contract file (JSON)
- Publish contract to Pact Broker: pact-broker publish
- Consumer tests are fast: they run against a local mock server
Provider Side:
- Use @pact-foundation/pact to verify against published contracts
- Provider verifier replays each consumer interaction against the real API
- Use provider states to set up test data: "given user exists with id 123"
- Run provider verification in CI on every provider change
- Use webhook from Pact Broker to trigger provider verification when contract changes
Best Practices:
- Test the contract, not the business logic (that belongs in unit tests)
- Keep interactions minimal: only assert on fields the consumer actually uses
- Use matchers for flexible assertions: like('string'), eachLike([]), integer()
- Version contracts with consumer app version for traceability
- Use tags for environment tracking: 'main', 'staging', 'production'
Can-I-Deploy:
- Use pact-broker can-i-deploy before deploying any service
- Checks if all contracts are verified and compatible
- Integrate into CI/CD pipeline as a deployment gate
- Prevents deploying a consumer that depends on an unverified provider change
- Works bidirectionally: checks both consumer and provider compatibility
Add to your project root CLAUDE.md file, or append to an existing one.