api-test-suite-generator
Generates comprehensive API test suites using Jest, Vitest, or Supertest from Express, Next.js, Fastify, or other API routes. Creates integration tests…
от patricio0312rev★ 64 звезды на GitHub
Установить api-test-suite-generator в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
API Test Suite Generator
Generate comprehensive API test suites automatically from your route definitions.
Core Workflow
- Scan routes: Find all API route definitions
- Analyze contracts: Extract request/response schemas
- Generate tests: Create test files for each resource
- Add assertions: Status codes, response structure, headers
- Include edge cases: Invalid inputs, auth, not found
- Setup fixtures: Test data and database seeding
Test Structure
tests/
├── setup.ts # Global test setup
├── fixtures/ # Test data
│ ├── users.ts
│ └── products.ts
├── integration/ # API integration tests
│ ├── users.test.ts
│ ├── products.test.ts
│ └── auth.test.ts
└── helpers/ # Test utilities
├── api-client.ts
└── auth.ts
Test Setup (Vitest/Jest)
// tests/setup.ts
import { beforeAll, afterAll, beforeEach, afterEach } from "vitest";
import { createServer } from "../src/server";
import { prisma } from "../src/db";
let server: ReturnType<typeof createServer>;
beforeAll(async () => {
server = await createServer();
await server.listen({ port: 0 }); // Random port
process.env.TEST_BASE_URL = `http://localhost:${server.address().port}`;
});
afterAll(async () => {
await server.close();
await prisma.$disconnect();
});
beforeEach(async () => {
// Clean database before each test
await prisma.$executeRaw`TRUNCATE TABLE users CASCADE`;
});
afterEach(async () => {
// Cleanup after each test
});
export { server };
API Test Client
// tests/helpers/api-client.ts
import supertest from "supertest";
const baseUrl = process.env.TEST_BASE_URL || "http://localhost:3000";
export const api = supertest(baseUrl);
export async function authenticatedApi(token?: string) {
const authToken = token || (await getTestAuthToken());
return {
get: (url: string) => api.get(url).set("Authorization", `Bearer ${authToken}`),
post: (url: string) => api.post(url).set("Authorization", `Bearer ${authToken}`),
put: (url: string) => api.put(url).set("Authorization", `Bearer ${authToken}`),
patch: (url: string) => api.patch(url).set("Authorization", `Bearer ${authToken}`),
delete: (url: string) => api.delete(url).set("Authorization", `Bearer ${authToken}`),
};
}
async function getTestAuthToken(): Promise<string> {
const response = await api.post("/api/auth/login").send({
email: "[email protected]",
password: "testpassword",
});
return response.body.token;
}
Test Generator Script
// scripts/generate-api-tests.ts
import * as fs from "fs";
import * as path from "path";
interface RouteInfo {
method: string;
path: string;
name: string;
params?: { name: string; type: "path" | "query" }[];
requestBody?: object;
responseSchema?: object;
auth?: boolean;
}
interface TestCase {
name: string;
description: string;
method: string;
path: string;
body?: object;
expectedStatus: number;
expectedBody?: object;
headers?: Record<string, string>;
auth?: boolean;
}
function generateTestFile(
resource: string,
routes: RouteInfo[]
): string {
const lines: string[] = [];
// Imports
lines.push(`import { describe, it, expect, beforeEach, afterEach } from "vitest";`);
lines.push(`import { api, authenticatedApi } from "../helpers/api-client";`);
lines.push(`import { create${capitalize(resource)} } from "../fixtures/${resource}";`);
lines.push("");
// Test suite
lines.push(`describe("${capitalize(resource)} API", () => {`);
for (const route of routes) {
const testCases = generateTestCases(route);
lines.push(` describe("${route.method} ${route.path}", () => {`);
for (const testCase of testCases) {
lines.push(generateTestCase(testCase, route));
}
lines.push(` });`);
lines.push("");
}
lines.push(`});`);
return lines.join("\n");
}
function generateTestCases(route: RouteInfo): TestCase[] {
const cases: TestCase[] = [];
// Success case
cases.push({
name: `should ${getActionVerb(route.method)} successfully`,
description: `Happy path for ${route.method} ${route.path}`,
method: route.method,
path: route.path,
body: route.requestBody,
expectedStatus: getExpectedStatus(route.method),
auth: route.auth,
});
// Auth failure case (if auth required)
if (route.auth) {
cases.push({
name: "should return 401 without auth token",
description: "Unauthorized access attempt",
method: route.method,
path: route.path,
expectedStatus: 401,
auth: false,
});
}
// Not found case (if has path params)
if (route.params?.some((p) => p.type === "path")) {
cases.push({
name: "should return 404 for non-existent resource",
description: "Resource not found",
method: route.method,
path: route.path.replace(/:(\w+)/g, "non-existent-id"),
expectedStatus: 404,
auth: route.
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл api-test-suite-generator?
Generates comprehensive API test suites using Jest, Vitest, or Supertest from Express, Next.js, Fastify, or other API routes. Creates integration tests, contract tests, and edge case coverage. Use when users request "generate api tests", "create endpoint tests", "api test suite", or "integration tests for api".
Как установить скилл api-test-suite-generator?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл api-test-suite-generator запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
AnthropicGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
claude-api
AnthropicReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
algorithmic-art
AnthropicCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
mcp-integration
AnthropicThis skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…