Command Palette

Search for a command to run...

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

Contract Testing with Pact

БесплатноБез исполняемых скриптовНе проверен

Consumer-driven contract testing skill using Pact, covering consumer tests, provider verification, Pact Broker integration, and CI/CD workflows.

PramodDuttaот 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

  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

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

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

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

Сравнить Contract Testing with Pact с