mcpField
A
api-testing

api-testing

github.com/secondskyテスト・品質240897 回インストール5 週間前に更新
リポジトリ

api-testing について

TypeScript/JavaScript では Supertest、Python では httpx と pytest を使う HTTP API テストのスキルです。リクエスト、認証、エラー、GraphQL、応答時間の確認例を扱います。

主な機能

  1. 01Supertest による TypeScript/JavaScript テスト
  2. 02httpx と pytest による Python テスト
  3. 03認証とエラー応答のテスト
  4. 04GraphQL エンドポイントのテスト
  5. 05応答時間の検証

活用シーン

  1. 01HTTP エンドポイントのステータス確認
  2. 02ログイン後の認証済みリクエスト検証
  3. 03不正な入力に対するエラー確認
  4. 04GraphQL クエリと応答の確認

インストール

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

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

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

詳細

API テスト

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

TypeScript/JavaScript(Supertest)

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

# or: npm install -D supertest @types/supertest
基本設定
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',
    })
  })

  it('validates required fields', async () => {
    await request(app)
      .post('/api/users')
      .send({ name: 'John Doe' })
      .expect(400)
  })
})
リクエストメソッド
// GET
await request(app).get('/api/users').expect(200)

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

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

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

// Query parameters
await request(app)
  .get('/api/users')
  .query({ page: 1, limit: 10 })
  .expect(200)
認証テスト
describe('Authentication', () => {
  let authToken: string

  beforeAll(async () => {
    const response = await request(app)
      .post('/api/auth/login')
      .send({ email: '[email protected]', password: 'password123' })
      .expect(200)

    authToken = response.body.token
  })

  it('accesses protected endpoint', async () => {
    await request(app)
      .get('/api/protected')
      .set('Authorization', `Bearer ${authToken}`)
      .expect(200)
  })

  it('rejects without token', async () => {
    await request(app).get('/api/protected').expect(401)
  })
})
エラー処理
it('handles validation errors', async () => {
  const response = await request(app)
    .post('/api/users')
    .send({ email: 'invalid-email' })
    .expect(400)

  expect(response.body).toMatchObject({
    error: 'Validation failed',
    details: expect.any(Array),
  })
})

it('handles not found', async () => {
  await request(app).get('/api/users/999999').expect(404)
})

Python(httpx + pytest)

インストール
uv add --dev httpx pytest-asyncio
基本設定
import pytest
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_not_found():
    response = client.get("/api/users/999")
    assert response.status_code == 404
フィクスチャ
@pytest.fixture
def auth_token(client):
    response = client.post(
        "/api/auth/login",
        json={"email": "[email protected]", "password": "password123"}
    )
    return response.json()["token"]

def test_protected_endpoint(client, auth_token):
    response = client.get(
        "/api/protected",
        headers={"Authorization": f"Bearer {auth_token}"}
    )
    assert response.status_code == 200
ファイルのアップロード
def test_file_upload(client, tmp_path):
    test_file = tmp_path / "test.txt"
    test_file.write_text("test content")

    with open(test_file, "rb") as f:
        response = client.post(
            "/api/upload",
            files={"file": ("test.txt", f, "text/plain")}
        )

    assert response.status_code == 200

GraphQL のテスト

it('queries GraphQL endpoint', async () => {
  const query = `
    query GetUser($id: ID!) {
      user(id: $id) { id name email }
    }
  `

  const response = await request(app)
    .post('/graphql')
    .send({ query, variables: { id: '1' } })
    .expect(200)

  expect(response.body.data.user).toMatchObject({
    id: '1',
    name: expect.any(String),
  })
})

パフォーマンステスト

it('responds within acceptable time', async () => {
  const start = Date.now()
  await request(app).get('/api/users').expect(200)
  const duration = Date.now() - start
  expect(duration).toBeLessThan(100) // 100ms threshold
})

ベストプラクティス

  • 関連するエンドポイントを describe ブロックにまとめます
  • テスト間でデータベースをリセットします
  • まずステータスコードを検証します
  • レスポンスの構造を確認します
  • エラーメッセージの形式をテストします
  • 外部サービスをモックします
  • 正常系とエラーケースの両方をテストします

関連項目

  • vitest-testing - ユニットテストフレームワーク
  • playwright-testing - E2E API テスト
  • test-quality-analysis - テスト品質のパターン

コメント