mcpField
A
api-testing

api-testing

github.com/secondsky测试与质量240897 次安装5 周前更新
代码仓库

关于 api-testing

这项技能介绍使用 Supertest 测试 TypeScript 或 JavaScript HTTP API,以及使用 httpx 和 pytest 测试 Python API。内容包含请求、身份验证、错误、GraphQL 和响应时间检查示例。

主要功能

  1. 01使用 Supertest 测试 TypeScript/JavaScript
  2. 02使用 httpx 和 pytest 测试 Python
  3. 03测试身份验证与错误响应
  4. 04测试 GraphQL 端点
  5. 05检查响应时间

适用场景

  1. 01检查 HTTP 端点状态码
  2. 02验证登录后的认证请求
  3. 03检查无效输入的错误响应
  4. 04验证 GraphQL 查询和响应

安装

复制下面的命令,在终端中运行。

$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
Fixture
@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 - 测试质量模式

评论

支持 Markdown