All Prompts
intermediate
REST API Tests with Supertest & Jest
Generate a production-grade API test suite using Supertest and Jest covering happy paths, validation errors, auth, RBAC, and DB isolation — with Zod response shape validation.
Prompt Template
You are an expert SDET specialising in Node.js API testing.
API name: {{apiName}}
Stack: {{stack}} (Express / Fastify / Next.js API routes)
Auth method: {{authMethod}}
Endpoints to test: {{endpoints}}
Generate a complete test suite using **Supertest + Jest** with the following structure:
**Test setup (jest.setup.ts / beforeAll):**
- Start the Express/Fastify app on a random port
- Run database migrations against a test database
- Seed baseline test data
- Generate auth tokens for each role (admin, user, guest)
**Per-endpoint tests (for each entry in {{endpoints}}):**
| Scenario | Expected |
|---|---|
| Happy path with valid payload | 200/201 + correct response shape |
| Missing required field | 400 + field-level error message |
| Invalid field type/format | 400 + specific validation error |
| No auth token | 401 |
| Wrong role (RBAC) | 403 |
| Resource not found | 404 |
| Duplicate resource | 409 (where applicable) |
| Payload too large | 413 (where applicable) |
**Response shape validation:**
- Define Zod schemas for every endpoint response
- Use `schema.parse(res.body)` — test fails if shape drifts from expectation
**Database isolation:**
- Wrap each test in a transaction that rolls back after the test
- Use a test-specific DB URL (never hit staging/prod)
**Auth helpers (utils/auth.ts):**
- `getAdminToken()`, `getUserToken(role)` — generate valid JWTs / session tokens
- `createTestUser(overrides)` — factory for test user creation
**File structure:**
```
__tests__/api/
{{resource}}.test.ts (one file per resource)
utils/
auth.ts
db.ts
factories.ts
```Tags
supertest
jest
rest-api
node
zod
database-isolation