mcpField
A
api-testing

api-testing

github.com/laurigatesテスト・品質59106 回インストール今日更新
リポジトリ

api-testing について

TypeScript/JavaScriptやPythonでHTTP APIテストを書く開発者向けのスキルです。リクエストとレスポンス、認証、エラー、連携状態を検証する例を扱います。

主な機能

  1. 01Supertestによるエンドポイントテスト
  2. 02httpxとpytestによるテスト
  3. 03リクエストとレスポンスの検証
  4. 04認証とエラーの確認
  5. 05データベースやサービスとの連携

活用シーン

  1. 01ExpressまたはFastifyのエンドポイントテスト
  2. 02Python REST/GraphQL APIのテスト
  3. 03認証フローやエラーレスポンスの確認

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/laurigates/claude-plugins --skill api-testing

インストール後、Claude Code で/api-testingを入力して読み込まれたか確認します。

同梱ファイルREFERENCE.md

詳細

API テスト

Supertest(TypeScript/JavaScript)および httpx/pytest(Python)を使用した HTTP API のテストに関する専門知識です。

このスキルを使用するタイミング

次のような場合にこのスキルを使用します...次のような場合は代わりに configure-plugin:configure-api-tests を使用します...
Express/Fastify アプリのエンドポイントテストを Supertest で作成するPact のコンシューマー/プロバイダー契約テストのインフラストラクチャをセットアップする
Python REST/GraphQL API のテストを httpx + pytest で作成するOpenAPI 仕様を検証する、またはスキーマ(Zod/AJV)チェックを CI に組み込む
テストコードでリクエスト/レスポンスの形式、ステータスコード、認証フローを検証するプロジェクトの API 契約テストツールを監査する、またはそのひな形を作成する
機能テストでエラー処理(4xx/5xx)と統合状態を検証するCI に破壊的変更の検出ワークフローを追加する

中核となる専門知識

API テスト機能

  • リクエストテスト:ヘッダー、クエリパラメーター、リクエストボディ
  • レスポンス検証:ステータスコード、ヘッダー、JSON スキーマ
  • 認証:Bearer トークン、Cookie、OAuth フロー
  • エラー処理:4xx/5xx レスポンス、検証エラー
  • 統合:データベースの状態、外部サービス
  • パフォーマンス:レスポンス時間、負荷テストの基礎

TypeScript/JavaScript(Supertest)

インストール
# Using Bun
bun add -d supertest @types/supertest

# Using npm
npm install -D supertest @types/supertest
Express を使用した基本設定
// app.ts
import express from 'express'

export const app = express()
app.use(express.json())

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok' })
})

app.post('/api/users', (req, res) => {
  const { name, email } = req.body
  if (!name || !email) {
    return res.status(400).json({ error: 'Missing required fields' })
  }
  res.status(201).json({ id: 1, name, email })
})
// app.test.ts
import { describe, it, expect } from 'vitest'
import request from 'supertest'
import { app } from './app'

describe('API Tests', () => {
  it('returns health status', async () => {
    const response = await request(app)
      .get('/api/health')
      .expect(200)

    expect(response.body).toEqual({ status: 'ok' })
  })

  it('creates a user', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ name: 'John Doe', email: '[email protected]' })
      .expect(201)

    expect(response.body).toMatchObject({
      id: expect.any(Number),
      name: 'John Doe',
      email: '[email protected]',
    })
  })

  it('validates required fields', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ name: 'John Doe' })
      .expect(400)

    expect(response.body.error).toBeDefined()
  })
})
リクエストメソッド
import request from 'supertest'
import { app } from './app'

// GET request
await request(app).get('/api/users').expect(200)

// POST request with body
await request(app).post('/api/users')
  .send({ name: 'John', email: '[email protected]' }).expect(201)

// PUT request
await request(app).put('/api/users/1')
  .send({ name: 'Jane' }).expect(200)

// PATCH request
await request(app).patch('/api/users/1')
  .send({ email: '[email protected]' }).expect(200)

// DELETE request
await request(app).delete('/api/users/1').expect(204)
ヘッダーとクエリパラメーター
// Set headers
await request(app)
  .get('/api/protected')
  .set('Authorization', 'Bearer token123')
  .set('Content-Type', 'application/json')
  .expect(200)

// Query parameters
await request(app)
  .get('/api/users')
  .query({ page: 1, limit: 10 })
  .expect(200)
レスポンスのアサーション
describe('Response validation', () => {
  it('validates status code', async () => {
    await request(app).get('/api/users').expect(200)
  })

  it('validates headers', async () => {
    await request(app).get('/api/users')
      .expect('Content-Type', /json/).expect(200)
  })

  it('validates response body', async () => {
    const response = await request(app).get('/api/users/1').expect(200)
    expect(response.body).toEqual({
      id: 1,
      name: 'John Doe',
      email: '[email protected]',
      createdAt: expect.any(String),
    })
  })

  it('validates array responses', async () => {
    const response = await request(app).get('/api/users').expect(200)
    expect(response.body).toBeInstanceOf(Array)
    expect(response.body).toHaveLength(5)
    expect(response.body[0]).toHaveProperty('id')
  })
})

Python(httpx + pytest)

インストール
# Using uv
uv add --dev httpx pytest-asyncio

# Using pip
pip install httpx pytest-asyncio
FastAPI を使用した基本設定
# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    name: str
    email: str

@app.get("/api/health")
def health_check():
    return {"status": "ok"}

@app.post("/api/users", status_code=201)
def create_user(user: User):
    return {"id": 1, "name": user.name, "email": user.email}

@app.get("/api/users/{user_id}")
def get_user(user_id: int):
    if user_id == 999:
        raise HTTPException(status_code=404, detail="User not found")
    return {"id": user_id, "name": "John Doe", "email": "[email protected]"}
# test_main.py
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_health_check():
    response = client.get("/api/health")
    assert response.status_code == 200
    assert response.json() == {"status": "ok"}

def test_create_user():
    response = client.post(
        "/api/users",
        json={"name": "John Doe", "email": "[email protected]"}
    )
    assert response.status_code == 201
    data = response.json()
    assert data["name"] == "John Doe"
    assert "id" in data

def test_validation_error():
    response = client.post("/api/users", json={"name": "John"})
    assert response.status_code == 422  # FastAPI validation error

def test_not_found():
    response = client.get("/api/users/999")
    assert response.status_code == 404

認証テスト、ファイルのアップロード、Cookie テスト、データベース統合、スキーマ検証、GraphQL テスト、パフォーマンステスト、ベストプラクティス、トラブルシューティングを含む詳しい例については、REFERENCE.md を参照してください。

エージェント向けの最適化

コンテキストコマンド
クイックテスト(Bun)bun test --dots --bail=1 api
クイックテスト(pytest)pytest -x --tb=short tests/api/
単一のテストファイルを実行bun test --dots path/to/test.ts
失敗時に詳細を表示bun test --bail=1 api

関連項目

  • vitest-testing - 単体テストフレームワーク
  • python-testing - Python の pytest パターン
  • playwright-testing - E2E API テスト
  • test-quality-analysis - テスト品質パターン

参考資料

コメント