Contract Testing with Pact
БесплатноБез исполняемых скриптовНе проверенConsumer-driven contract testing skill using Pact, covering consumer tests, provider verification, Pact Broker integration, and CI/CD workflows.
от PramodDutta★ 253 звезды на GitHubОб этом скилле
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
- Consumer-driven -- The consumer defines the contract; the provider must honor it.
- Pact as contract -- Pact files are the single source of truth for API compatibility.
- Independent deployability -- Contract tests ensure services can be deployed independently.
- Broker as hub -- The Pact Broker mediates contract sharing and verification tracking.
- 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
npm install --save-dev @pact-foundation/pact
Consumer API Client
// 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
// 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@]+$/, '[email protected]'),
name: string('John Doe'),
role: regex(/^(admin|user|viewer)$/, 'user'),
},
});
// Act & Assert: Execute against the mock provider
await provider.executeTest(async (mockServer) => {
const client =
Установить Contract Testing with Pact в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Contract Testing with Pact?
Consumer-driven contract testing skill using Pact, covering consumer tests, provider verification, Pact Broker integration, and CI/CD workflows.
Как установить скилл Contract Testing with Pact?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Contract Testing with Pact запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
ci-review
The scan that the plugin's GitHub Action runs.
от Anthropicazure-static-web-apps
Helps create, configure, and deploy Azure Static Web Apps using the SWA CLI. Use when deploying static sites to Azure, setting up SWA local development…
от GitHubai-ready
Make any repo AI-ready — analyzes your codebase and generates AGENTS.md, copilot-instructions.md, CI workflows, issue templates, and more. Mines your PR…
от GitHubaws-cdk-python-setup
Setup and initialization guide for developing AWS CDK (Cloud Development Kit) applications in Python. This skill enables users to configure environment…
от GitHub