pact
БесплатноБез исполняемых скриптовНе проверенSets up consumer-driven contract testing with Pact JS: a consumer test that writes a pact file, a provider verification that replays it, and a Pact Broker or…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Pact Contract Testing (Pact JS)
Overview
A contract test answers one question: will this consumer keep working against that provider, without starting both? The consumer test runs the real client code against a Pact mock server, and what the client sent and expected is saved as a pact file. The provider later replays that file against its real API. If both sides pass, the contract holds. A broker stores the pacts and verification results, and can-i-deploy uses them to decide whether a version may ship.
Pact JS 17 (verified with 17.1.4) uses the V4 consumer API (PactV4) and the Verifier class. Matching rules come from MatchersV3.
Use it for HTTP/JSON services owned by different teams or deployed independently. Do not use it for third-party APIs you cannot ask to verify, for load or latency checks, or as a replacement for testing business logic inside the provider.
Instructions
1. Ask and look up first
Ask only what the project cannot tell you: which service is the consumer, which is the provider, whether a broker exists (URL, token in an environment variable), and how the provider is started in tests. Look up the HTTP client the consumer uses, its test runner, the provider framework, and the CI system.
Decide the names once. Consumer and provider names become part of the pact file name and the broker, so use the deployable service names (storefront-web, parcel-tracker), not team names.
2. Install
npm install --save-dev @pact-foundation/pact vitest
Node 22 or newer is required. Pact files are written to ./pacts unless dir says otherwise; add pacts/ to .gitignore when a broker is used.
3. Write the consumer test
Cover only what the consumer really reads. Every extra field in the expectation becomes a demand on the provider.
import path from 'node:path';
import { describe, it, expect } from 'vitest';
import { PactV4, MatchersV3 } from '@pact-foundation/pact';
import { ShipmentClient } from '../src/shipment-client.js';
const { like, regex, eachLike, timestamp } = MatchersV3;
const pact = new PactV4({
consumer: 'storefront-web',
provider: 'parcel-tracker',
dir: path.resolve(process.cwd(), 'pacts'),
});
describe('parcel-tracker contract', () => {
it('returns a parcel that exists', () =>
pact
.addInteraction()
.given('parcel TRK-48213 is in transit')
.uponReceiving('a request for parcel TRK-48213')
.withRequest('GET', '/parcels/TRK-48213', (b) =>
b.headers({
Accept: 'application/json',
Authorization: regex(/^Bearer .+$/, 'Bearer tok-7f3a'),
}),
)
.willRespondWith(200, (b) =>
b.headers({ 'Content-Type': 'application/json' }).jsonBody({
trackingCode: 'TRK-48213',
status: regex(/^(label_created|in_transit|delivered)$/, 'in_transit'),
updatedAt: timestamp("yyyy-MM-dd'T'HH:mm:ss'Z'", '2026-10-12T09:30:00Z'),
events: eachLike({ city: like('Rotterdam'), code: like('ARR') }),
}),
)
.executeTest(async (mockServer) => {
const client = new ShipmentClient(mockServer.url, 'tok-7f3a');
const parcel = await client.getParcel('TRK-48213');
expect(parcel.status).toBe('in_transit');
}));
});
Rules that keep contracts honest:
- The client under test must take its base URL from a parameter, so the test can pass
mockServer.url. .given(...)names a provider state. Write it as a sentence the provider team can implement ("parcel TRK-48213 is in transit").- Use matchers (
like,regex,eachLike,timestamp) for values that vary; exact values for things the consumer branches on. - Add one interaction per distinct response the consumer handles: success, not found, validation error, unauthorized.
- The mock server verifies the request too. If the client sends something different,
executeTestthrows.
After vitest run, pacts/storefront-web-parcel-tracker.json exists. Open it once and check that matching rules appear under matchingRules and that no secret is in it (use a fake token).
4. Verify on the provider side
Run the real provider with its dependencies stubbed, and map each provider state to setup code.
import { describe, it } from 'vitest';
import { Verifier } from '@pact-foundation/pact';
import { buildApp, parcelStore } from '../src/app.js';
describe('parcel-tracker provider verification', () => {
it('honours every consumer pact', async () => {
const server = buildApp().listen(0);
const { port } = server.address();
try {
await new Verifier({
provider: 'parcel-tracker',
providerBaseUrl: `http://127.0.0.1:${port}`,
pactUrls: ['./pacts/storefront-web-parcel-tracker.json'],
stateHandlers: {
'parcel TRK-48213 is in transit': async () => {
await parcelStore.reset();
await parcelStore.insert({ trackingCode: 'TRK-48213', status: 'in_transit' });
},
'n
Установить pact в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл pact?
Sets up consumer-driven contract testing with Pact JS: a consumer test that writes a pact file, a provider verification that replays it, and a Pact Broker or PactFlow with can-i-deploy in CI. Use when the user mentions "pact", "contract testing", "consumer-driven contracts", "provider verification", "can-i-deploy", "Pact Broker" or wants to stop two services breaking each other without end-to-end tests.
Как установить скилл pact?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл pact запускает скрипты?
Нет, скилл состоит только из инструкций (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