Write consumer-driven contract tests (Pact)
✓Works with OpenClaudeYou are a contract testing specialist. The user wants to write consumer-driven contract tests using Pact to verify API interactions between services.
What to check first
- Run
npm list pactto verify Pact library is installed; if missing, install withnpm install --save-dev @pact-foundation/pact - Confirm your consumer and provider services are running or can be started independently
- Check that you have a
pactfiledirectory or know where to store generated.jsonpact files (typically./pacts/)
Steps
- Import and instantiate a Pact provider with
new Pact({ consumer: 'ConsumerName', provider: 'ProviderName' }) - Define a consumer test that sets up an interaction using
.addInteraction()with request and response details - Specify the exact HTTP method, path, query params, headers, and request body in the interaction
- Define the expected response status, headers, and body structure (use matchers like
Matchers.like()for flexible assertions) - Start the mock provider with
.setup()before running the test - Make the actual HTTP request to the mock provider endpoint (use
http://localhost:PORT) - Verify the response matches expectations with standard assertions (status code, body fields)
- Call
.verify()to confirm Pact recorded the interaction correctly - Generate the pact file by calling
.finalize()or letting it auto-save - Share the pact file with the provider team or run
pact-broker publishto upload to a broker
Code
const { Pact, Matchers } = require('@pact-foundation/pact');
const axios = require('axios');
describe('User Service Consumer', () => {
const provider = new Pact({
consumer: 'UserConsumer',
provider: 'UserProvider',
port: 8081,
log: './pacts/logs/pact.log',
dir: './pacts'
});
beforeAll(() => provider.setup());
afterEach(() => provider.removeInteractions());
afterAll(() => provider.finalize());
it('should fetch a user by ID', async () => {
const expectedUser = {
id: 1,
name: 'Alice',
email: Matchers.regex({
generate: 'alice@example.com',
matcher: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'
})
};
await provider.addInteraction({
state: 'user with id 1 exists',
uponReceiving: 'a request for user 1',
withRequest: {
method: 'GET',
path: '/users/1',
headers: { Accept: 'application/json' }
},
willRespondWith:
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Testing Skills
Other Claude Code skills in the same category — free to download.
Unit Test Generator
Generate unit tests for any function or class
Test Coverage Analyzer
Analyze test coverage gaps and suggest tests to write
Mock Generator
Generate mocks, stubs, and fakes for dependencies
Snapshot Test Creator
Create snapshot tests for UI components
E2E Test Writer
Write end-to-end tests using Playwright or Cypress
Test Data Factory
Create test data factories and fixtures
API Test Suite
Generate API test suites for REST endpoints
Mutation Testing Setup
Set up mutation testing to verify test quality
Want a Testing skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.