Contract Testing with Pact
Consumer-driven contract testing skill using Pact, covering consumer tests, provider verification, Pact Broker integration, and CI/CD workflows.
git clone --depth 1 https://github.com/PramodDutta/qaskills /tmp/contract-testing-with-pact && cp -r /tmp/contract-testing-with-pact/seed-skills/contract-testing-pact ~/.claude/skills/contract-testing-with-pactSKILL.md
# Contract Testing with Pact Skill
You are an expert QA engineer specializing in consumer-driven contract testing with Pact. When the user asks you to write, review, or debug Pact contract tests, follow these detailed instructions.
## Core Principles
1. **Consumer-driven** -- The consumer defines the contract; the provider must honor it.
2. **Pact as contract** -- Pact files are the single source of truth for API compatibility.
3. **Independent deployability** -- Contract tests ensure services can be deployed independently.
4. **Broker as hub** -- The Pact Broker mediates contract sharing and verification tracking.
5. **Can-i-deploy** -- Always verify deployment compatibility before deploying to production.
## How Pact Works
```
Consumer Side Provider Side
┌─────────────┐ ┌─────────────┐
│ Consumer │ │ Provider │
│ Test │ │ Test │
│ │ │ │
│ 1. Define │ Pact File │ 3. Verify │
│ expected │ ─────────────> │ against │
│ behavior │ │ running │
│ │ │ service │
│ 2. Generate │ │ │
│ Pact │ │ 4. Publish │
│ file │ │ results │
└─────────────┘ └─────────────┘
│ │
│ ┌───────────────┐ │
└──────>│ Pact Broker │<──────┘
│ │
│ Stores pacts │
│ Tracks │
│ verification │
│ can-i-deploy │
└───────────────┘
```
## Project Structure (TypeScript Consumer)
```
consumer-service/
src/
clients/
user-api-client.ts
product-api-client.ts
models/
user.model.ts
tests/
contract/
user-api.consumer.pact.spec.ts
product-api.consumer.pact.spec.ts
pacts/ <-- Generated Pact files
consumer-user-service.json
jest.config.ts
package.json
```
## Project Structure (TypeScript Provider)
```
provider-service/
src/
routes/
users.routes.ts
services/
user.service.ts
tests/
contract/
user-api.provider.pact.spec.ts
utils/
provider-states.ts
jest.config.ts
package.json
```
## Consumer Test (TypeScript)
### Setup
```bash
npm install --save-dev @pact-foundation/pact
```
### Consumer API Client
```typescript
// src/clients/user-api-client.ts
import axios, { AxiosInstance } from 'axios';
export interface User {
id: string;
email: string;
name: string;
role: string;
}
export interface CreateUserRequest {
email: string;
name: string;
password: string;
}
export class UserApiClient {
private http: AxiosInstance;
constructor(baseUrl: string) {
this.http = axios.create({ baseUrl });
}
async getUser(id: string): Promise<User> {
const response = await this.http.get(`/api/users/${id}`);
return response.data;
}
async createUser(data: CreateUserRequest): Promise<User> {
const response = await this.http.post('/api/users', data);
return response.data;
}
async listUsers(page: number = 1): Promise<{ data: User[]; total: number }> {
const response = await this.http.get(`/api/users?page=${page}`);
return response.data;
}
async deleteUser(id: string): Promise<void> {
await this.http.delete(`/api/users/${id}`);
}
}
```
### Consumer Pact Test
```typescript
// tests/contract/user-api.consumer.pact.spec.ts
import { PactV3, MatchersV3 } from '@pact-foundation/pact';
import path from 'path';
import { UserApiClient } from '../../src/clients/user-api-client';
const { like, eachLike, string, uuid, integer, regex } = MatchersV3;
const provider = new PactV3({
consumer: 'frontend-app',
provider: 'user-service',
dir: path.resolve(process.cwd(), 'tests/pacts'),
logLevel: 'warn',
});
describe('User API Consumer Contract', () => {
describe('GET /api/users/:id', () => {
it('should return a user when the user exists', async () => {
// Arrange: Define the expected interaction
provider
.given('a user with ID user-123 exists')
.uponReceiving('a request to get a user by ID')
.withRequest({
method: 'GET',
path: '/api/users/user-123',
headers: {
Accept: 'application/json',
},
})
.willRespondWith({
status: 200,
headers: {
'Content-Type': 'application/json',
},
body: {
id: like('user-123'),
email: regex(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, 'user@example.com'),
name: string('John Doe'),
role: regex(/^(admin|user|viewer)$/, 'user'),
},
});
// Act & Assert: Execute against the mock provider
await provider.executeTest(async (mockServer) => {
const client = new UserApiClient(mockServer.url);
const user = await client.getUser('user-123');
expect(user.id).toBe('user-123');
expect(user.email).toBeDefined();
expect(user.name).toBeDefined();
expect(user.role).toBeDefined();
});
});
it('should return 404 when the user does not exist', async () => {
provider
.given('no user with ID nonexistent exists')
.uponReceiving('a request to get a non-existent user')
.withRequest({
method: 'GET',
path: '/api/users/nonexistent',
headers: {
Accept: 'application/json',
},
})
.willRespondWith({
status: 404,
headers: {
'Content-Type': 'application/json',
},
body: {
message: string('User not found'),
statusCode: integer(404),
},
});
await provider.executeTest(async (mockServer) => {
const client = newAutomated accessibility testing with axe-core integrated into CI pipelines, including custom rule configuration, issue prioritization, and remediation guidance.
Validating A/B test implementations including traffic splitting accuracy, statistical significance calculation, metric tracking, and experiment cleanup.
Comprehensive WCAG compliance and accessibility testing covering ARIA, keyboard navigation, screen readers, color contrast, and automated a11y validation.
Comprehensive WCAG 2.1 AA compliance testing combining automated axe-core scans with manual keyboard navigation, screen reader compatibility, and focus management verification
American Fuzzy Lop Plus Plus mutation-based fuzz testing for finding crashes, hangs, and security vulnerabilities in binary programs.
Fast Rust-based headless browser automation CLI with Node.js fallback for AI agents, featuring navigation, clicking, typing, snapshots, and structured commands optimized for agent workflows.
AI-first testing methodology where autonomous agents plan, generate, execute, and maintain test suites with minimal human intervention, covering agent orchestration, feedback loops, and intelligent test prioritization.
Comprehensive evaluation patterns for AI agents including multi-turn conversation testing, LLM-as-judge frameworks, benchmark suites, regression detection, and systematic eval pipelines for measuring agent quality and safety.