Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

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от 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, executeTest throws.

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
Полный SKILL.md на GitHub

Установить pact в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

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), без исполняемых скриптов.

Похожие скиллы

Сравнить pact с