contract-testing
БесплатноБез исполняемых скриптовНе проверенUse when setting up or improving contract tests that verify API compatibility between services. Covers Pact (consumer-driven contracts), PactFlow…
от onfire7777★ 17 звёзд на GitHubОб этом скилле
Contract Testing — Verifying API Compatibility Between Services
Overview
Contract testing verifies that two services (a consumer and a provider) can communicate correctly without requiring both to be running simultaneously. Instead of testing the full integration, each side verifies against a contract — a formal specification of the expected request/response interactions.
When to use contract tests instead of E2E: In microservices architectures where E2E tests become too slow, too flaky, and too expensive to maintain across dozens of services.
Contract Testing Approaches
| Approach | How It Works | Best For |
|---|---|---|
| Consumer-Driven | Consumer writes the contract, provider verifies it | Most common — consumer knows what it needs |
| Provider-Driven | Provider publishes its API spec, consumers verify against it | APIs with many unknown consumers |
| Bi-Directional | Both sides verify against a shared spec (e.g., OpenAPI) | Teams that already maintain OpenAPI specs |
Consumer-Driven Contract Testing (Pact Workflow)
Consumer Pact Broker Provider
│ │ │
├─ 1. Write consumer test ──►│ │
│ (generates pact file) │ │
│ │ │
├─ 2. Publish pact ─────────►│ │
│ │ │
│ │◄── 3. Fetch pact ──────────┤
│ │ │
│ │ 4. Provider verifies ───►│
│ │ against pact │
│ │ │
│ │◄── 5. Publish result ──────┤
│ │ │
├── 6. can-i-deploy? ──────►│ │
│ (checks compatibility) │ │
│ │ │
Pact
Pact is the most widely used contract testing framework, supporting consumer-driven contracts across many languages.
JavaScript — Consumer Test
// consumer/user-client.pact.test.ts
import { PactV4, MatchersV3 } from '@pact-foundation/pact';
import { UserClient } from './user-client';
const { like, eachLike, regex, integer, string } = MatchersV3;
const provider = new PactV4({
consumer: 'UserWebApp',
provider: 'UserService',
logLevel: 'warn',
});
describe('UserClient', () => {
it('should fetch a user by ID', async () => {
// Define the expected interaction
await provider
.addInteraction()
.given('user 123 exists')
.uponReceiving('a request for user 123')
.withRequest('GET', '/api/users/123', (builder) => {
builder.headers({ Accept: 'application/json' });
})
.willRespondWith(200, (builder) => {
builder
.headers({ 'Content-Type': 'application/json' })
.jsonBody({
id: integer(123),
name: string('Alice'),
email: regex('[email protected]', '^[\\w.-]+@[\\w.-]+\\.[a-z]{2,}$'),
role: string('admin'),
});
})
.executeTest(async (mockServer) => {
// Point the client at the mock server
const client = new UserClient(mockServer.url);
// Call the client — it talks to the Pact mock
const user = await client.getUser(123);
// Verify the client handles the response correctly
expect(user.id).toBe(123);
expect(user.name).toBe('Alice');
expect(user.email).toBe('[email protected]');
});
});
it('should fetch a list of users', async () => {
await provider
.addInteraction()
.given('users exist')
.uponReceiving('a request for all users')
.withRequest('GET', '/api/users', (builder) => {
builder.headers({ Accept: 'application/json' });
})
.willRespondWith(200, (builder) => {
builder
.headers({ 'Content-Type': 'application/json' })
.jsonBody(
eachLike({
id: integer(1),
name: string('Alice'),
email: string('[email protected]'),
})
);
})
.executeTest(async (mockServer) => {
const client = new UserClient(mockServer.url);
const users = await client.listUsers();
expect(users).toHaveLength(1);
expect(users[0].name).toBe('Alice');
});
});
it('should return 404 for non-existent user', async () => {
await provider
.addInteraction()
.given('user 999 does not exist')
.uponReceiving('a request for user 999')
.withRequest('GET', '/api/users/999')
.willRespondWith(404, (builder) => {
builder
Установить contract-testing в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл contract-testing?
Use when setting up or improving contract tests that verify API compatibility between services. Covers Pact (consumer-driven contracts), PactFlow (bi-directional contracts), Spring Cloud Contract, Pact Broker, can-i-deploy, and strategies for choosing between contract testing approaches. USE FOR: Pact, PactFlow, Spring Cloud Contract, consumer-driven contracts, bi-directional contracts, API compatibility verification, can-i-deploy, Pact Broker DO NOT USE FOR: full user flow tests (use e2e-testing), API functional testing (use api-testing), unit testing (use unit-testing)
Как установить скилл contract-testing?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл contract-testing запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic