| name | api-test-suite-generator |
| description | 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
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)
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 });
process.env.TEST_BASE_URL = `http://localhost:${server.address().port}`;
});
afterAll(async () => {
await server.close();
await prisma.$disconnect();
});
beforeEach(async () => {
await prisma.$executeRaw`TRUNCATE TABLE users CASCADE`;
});
afterEach(async () => {
});
export { server };
API Test Client
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: () => api.(url).(, ),
: api.(url).(, ),
};
}
(): <> {
response = api.().({
: ,
: ,
});
response..;
}
Test Generator Script
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: ,
: []
): {
: [] = [];
lines.();
lines.();
lines.();
lines.();
lines.();
( route routes) {
testCases = (route);
lines.();
( testCase testCases) {
lines.((testCase, route));
}
lines.();
lines.();
}
lines.();
lines.();
}
(): [] {
: [] = [];
cases.({
: ,
: ,
: route.,
: route.,
: route.,
: (route.),
: route.,
});
(route.) {
cases.({
: ,
: ,
: route.,
: route.,
: ,
: ,
});
}
(route.?.( p. === )) {
cases.({
: ,
: ,
: route.,
: route..(, ),
: ,
: route.,
});
}
([, , ].(route.)) {
cases.({
: ,
: ,
: route.,
: route.,
: {},
: ,
: route.,
});
}
cases;
}
(): {
: [] = [];
indent = ;
lines.();
(route.?.( p. === )) {
lines.();
lines.();
lines.();
} {
lines.();
}
lines.();
(testCase.) {
lines.();
lines.(
);
} {
lines.(
);
}
(testCase.) {
lines.();
}
lines.();
lines.();
(testCase. < ) {
lines.();
(testCase. === ) {
lines.();
}
} {
lines.();
}
lines.();
lines.();
lines.();
}
(): {
: <, > = {
: ,
: ,
: ,
: ,
: ,
};
verbs[method] || ;
}
(): {
: <, > = {
: ,
: ,
: ,
: ,
: ,
};
statuses[method] || ;
}
(): {
str.().() + str.();
}
Example Generated Tests
import { describe, it, expect, beforeEach } from "vitest";
import { api, authenticatedApi } from "../helpers/api-client";
import { createUser, createUsers } from "../fixtures/users";
describe("Users API", () => {
describe("GET /api/users", () => {
it("should return paginated list of users", async () => {
await createUsers(15);
const client = await authenticatedApi();
const response = await client
.get("/api/users")
.query({ page: 1, limit: 10 })
.expect(200);
expect(response.body.success).toBe(true);
expect(response.body.data).toHaveLength(10);
(response...).();
(response...).();
(response...).();
});
(, () => {
response = api.().();
(response...).();
});
});
(, {
(, () => {
user = ({ : });
client = ();
response = client
.()
.();
(response...).(user.);
(response...).();
});
(, () => {
client = ();
response = client
.()
.();
(response...).();
});
});
(, {
(, () => {
client = ();
response = client
.()
.({
: ,
: ,
: ,
})
.();
(response...).();
(response...).();
(response...).();
});
(, () => {
client = ();
response = client
.()
.({})
.();
(response...).();
(response...).();
});
(, () => {
({ : });
client = ();
response = client
.()
.({
: ,
: ,
})
.();
(response...).();
});
});
(, {
(, () => {
user = ({ : });
client = ();
response = client
.()
.({
: ,
: user.,
})
.();
(response...).();
});
(, () => {
client = ();
response = client
.()
.({ : })
.();
(response...).();
});
});
(, {
(, () => {
user = ();
client = ();
client.().();
client.().();
});
(, () => {
client = ();
client.().();
});
});
});
Test Fixtures
import { prisma } from "../../src/db";
import { faker } from "@faker-js/faker";
interface CreateUserOptions {
name?: string;
email?: string;
role?: string;
}
export async function createUser(options: CreateUserOptions = {}) {
return prisma.user.create({
data: {
name: options.name ?? faker.person.fullName(),
email: options.email ?? faker.internet.email(),
role: options.role ?? "user",
password: await hashPassword("testpassword"),
},
});
}
export async function createUsers(count: number) {
const users = Array.from({ length: count }, () => ({
: faker..(),
: faker..(),
: ,
: ,
}));
prisma..({ : users });
}
() {
({ : });
}
Contract Testing
import { describe, it, expect } from "vitest";
import { api, authenticatedApi } from "../helpers/api-client";
import { z } from "zod";
const UserSchema = z.object({
id: z.string().uuid(),
name: z.string(),
email: z.string().email(),
role: z.enum(["user", "admin"]),
createdAt: z.string().datetime(),
});
const PaginatedUsersSchema = z.object({
success: z.literal(true),
data: z.array(UserSchema),
meta: z.object({
page: z.number(),
limit: z.number(),
total: z.number(),
total_pages: z.number(),
}),
});
describe("Users API Contract", {
(, () => {
client = ();
response = client.().();
result = .(response.);
(result.).();
});
(, () => {
user = ();
client = ();
response = client.().();
result = .(response..);
(result.).();
});
});
CLI Script
#!/usr/bin/env node
import * as fs from "fs";
import * as path from "path";
import { program } from "commander";
program
.name("test-gen")
.description("Generate API test suite from routes")
.option("-f, --framework <type>", "Framework (express|nextjs|fastify)", "express")
.option("-s, --source <path>", "Source directory", "./src")
.option("-o, --output <path>", "Output directory", "./tests/integration")
.option("-t, --test-runner <type>", "Test runner (vitest|jest)", "vitest")
.parse();
const options = program.opts();
async function main() {
const routes = await scanRoutes(options.framework, options.source);
const groupedRoutes = groupRoutesByResource(routes);
if (!fs.existsSync(options.)) {
fs.(options., { : });
}
( [resource, resourceRoutes] .(groupedRoutes)) {
content = (resource, resourceRoutes);
filePath = path.(options., );
fs.(filePath, content);
.();
}
}
();
Best Practices
- Isolate tests: Each test should be independent
- Clean state: Reset database between tests
- Use fixtures: Create reusable test data factories
- Test edge cases: Invalid input, auth, not found
- Contract testing: Validate response schemas
- Descriptive names: Tests should read like documentation
- Fast execution: Use transactions for database cleanup
- CI integration: Run tests on every PR
Output Checklist