TypeScript API Testing with Supertest: Type-Safe HTTP Tests
Supertest lets you test HTTP APIs without spinning up a real server. Combined with TypeScript, you get type-checked request bodies, typed response assertions, and autocomplete on your test helpers. This guide shows how to set up Supertest with Express or Fastify in TypeScript, write type-safe integration tests, handle auth, seed test databases, and run everything cleanly in CI.
Key Takeaways
Pass your app, not a running server. supertest(app) — not a URL — lets Supertest manage the port and lifecycle. Your app file should export the Express/Fastify instance without calling .listen().
Type your response bodies. Use response.body as MyResponseType or a validation library like Zod to assert shapes, not just status codes.
Create typed request helpers. A makeAuthRequest(token) factory that returns a Supertest agent reduces boilerplate and keeps auth logic in one place.
Use beforeAll for DB seeding, afterAll for cleanup. Transaction rollbacks are faster than truncating tables — wrap each test in a transaction and roll back after.
Don't assert response.body.id as a string. TypeScript won't catch this at test time unless you actually type the response. Use Zod .parse() to validate and narrow in one step.
Why TypeScript + Supertest?
JavaScript API tests often degrade into a mess of any types and string-based assertions. You test that response.body.user.name equals "Alice" without TypeScript knowing what shape response.body has, what fields are required, or whether user can be null.
TypeScript changes the contract. When you type your request helpers and response parsers, the compiler enforces the same rules in tests that your application code must follow. Rename a field in your API response type, and every test asserting that field breaks at compile time — not at runtime in production.
Supertest is the de facto HTTP testing library for Node.js. It wraps http.createServer and lets you make requests against your Express, Fastify, Koa, or Hapi app without binding to a port.
Project Setup
Install the dependencies:
npm install --save-dev supertest @types/supertest
npm install --save-dev jest ts-jest @types/jestConfigure jest.config.ts:
import type { Config } from 'jest';
const config: Config = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/*.test.ts'],
setupFilesAfterFramework: ['<rootDir>/src/test/setup.ts'],
};
export default config;Exporting Your App Without Listening
The key to Supertest is passing the app instance, not a URL. Your app file should export the app without calling .listen():
// src/app.ts
import express from 'express';
import { userRouter } from './routes/users';
import { authRouter } from './routes/auth';
export const app = express();
app.use(express.json());
app.use('/users', userRouter);
app.use('/auth', authRouter);Your entry point calls .listen() separately:
// src/server.ts
import { app } from './app';
const PORT = process.env.PORT ?? 3000;
app.listen(PORT, () => console.log(`Listening on ${PORT}`));This pattern means tests import app and Supertest manages the server lifecycle. No ports, no cleanup.
Basic Type-Safe Tests
Define your response types (or reuse the same types your app uses):
// src/types/api.ts
export interface UserResponse {
id: string;
email: string;
name: string;
createdAt: string;
}
export interface ErrorResponse {
error: string;
code: string;
}
export interface PaginatedResponse<T> {
data: T[];
total: number;
page: number;
pageSize: number;
}Write your first test:
// src/routes/users.test.ts
import request from 'supertest';
import { app } from '../app';
import type { UserResponse, PaginatedResponse } from '../types/api';
describe('GET /users', () => {
it('returns a paginated list of users', async () => {
const response = await request(app)
.get('/users')
.expect(200)
.expect('Content-Type', /json/);
const body = response.body as PaginatedResponse<UserResponse>;
expect(body.data).toBeInstanceOf(Array);
expect(typeof body.total).toBe('number');
expect(typeof body.page).toBe('number');
});
it('returns 400 for invalid page parameter', async () => {
const response = await request(app)
.get('/users?page=abc')
.expect(400);
const body = response.body as ErrorResponse;
expect(body.error).toBeDefined();
expect(body.code).toBe('VALIDATION_ERROR');
});
});Using Zod for Runtime-Safe Response Validation
The as UserResponse cast is a lie — TypeScript trusts you, but the runtime doesn't check. For integration tests where you're asserting on actual response shapes, use Zod to validate and narrow simultaneously:
import { z } from 'zod';
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
name: z.string().min(1),
createdAt: z.string().datetime(),
});
const PaginatedUsersSchema = z.object({
data: z.array(UserSchema),
total: z.number().int().nonnegative(),
page: z.number().int().positive(),
pageSize: z.number().int().positive(),
});
describe('GET /users', () => {
it('returns valid paginated users', async () => {
const response = await request(app).get('/users').expect(200);
// Throws if shape doesn't match — test fails with a clear Zod error
const body = PaginatedUsersSchema.parse(response.body);
expect(body.data.length).toBeGreaterThanOrEqual(0);
expect(body.total).toBeGreaterThanOrEqual(body.data.length);
});
});Now if your API returns userId instead of id, the test fails immediately with ZodError: Required at "data[0].id" — not a cryptic undefined comparison.
Authentication Helpers
Most endpoints require auth. Instead of copy-pasting Authorization: Bearer ... into every test, build a typed helper:
// src/test/helpers.ts
import request, { Test, SuperTest } from 'supertest';
import { app } from '../app';
import { createTestUser, generateToken } from './fixtures';
export interface TestUser {
id: string;
email: string;
token: string;
}
export async function createAuthenticatedUser(
overrides: Partial<{ email: string; role: string }> = {}
): Promise<TestUser> {
const user = await createTestUser(overrides);
const token = generateToken(user.id);
return { ...user, token };
}
export function authedRequest(token: string): SuperTest<Test> {
return request(app).set('Authorization', `Bearer ${token}`) as SuperTest<Test>;
}Use it in tests:
describe('POST /users/:id/profile', () => {
let user: TestUser;
beforeAll(async () => {
user = await createAuthenticatedUser({ role: 'admin' });
});
it('updates the user profile', async () => {
const response = await authedRequest(user.token)
.patch(`/users/${user.id}/profile`)
.send({ name: 'Updated Name' })
.expect(200);
const body = response.body as UserResponse;
expect(body.name).toBe('Updated Name');
});
it('returns 403 for non-admin users', async () => {
const regularUser = await createAuthenticatedUser({ role: 'user' });
await authedRequest(regularUser.token)
.patch(`/users/${user.id}/profile`)
.send({ name: 'Hacked' })
.expect(403);
});
});Database Setup with Transaction Rollback
Integration tests that hit a real database need to manage state. The fastest approach is wrapping each test in a transaction and rolling back:
// src/test/setup.ts
import { db } from '../db';
beforeEach(async () => {
await db.query('BEGIN');
});
afterEach(async () => {
await db.query('ROLLBACK');
});
afterAll(async () => {
await db.end();
});This is faster than truncating tables (no DDL locks, no cascades) and leaves your database schema intact.
For Prisma, use the $transaction API with a rollback flag:
// src/test/prisma-rollback.ts
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export async function withRollback<T>(
fn: (tx: Omit<PrismaClient, '$connect' | '$disconnect' | '$on' | '$transaction' | '$use'>) => Promise<T>
): Promise<void> {
try {
await prisma.$transaction(async (tx) => {
await fn(tx);
throw new Error('__rollback__'); // Force rollback
});
} catch (e) {
if ((e as Error).message !== '__rollback__') throw e;
}
}Testing File Uploads
Supertest supports multipart form data:
import path from 'path';
describe('POST /users/:id/avatar', () => {
it('accepts a valid PNG upload', async () => {
const fixturePath = path.join(__dirname, 'fixtures', 'avatar.png');
const response = await authedRequest(user.token)
.post(`/users/${user.id}/avatar`)
.attach('avatar', fixturePath)
.expect(200);
const body = response.body as { avatarUrl: string };
expect(body.avatarUrl).toMatch(/^https:\/\//);
});
it('rejects non-image files', async () => {
const fixturePath = path.join(__dirname, 'fixtures', 'document.pdf');
await authedRequest(user.token)
.post(`/users/${user.id}/avatar`)
.attach('avatar', fixturePath)
.expect(422);
});
});Testing with Fastify
Fastify has its own test utilities that integrate tighter than Supertest:
import Fastify from 'fastify';
import { userPlugin } from '../plugins/users';
describe('User routes (Fastify)', () => {
const fastify = Fastify();
beforeAll(async () => {
await fastify.register(userPlugin);
await fastify.ready();
});
afterAll(() => fastify.close());
it('GET /users returns 200', async () => {
const response = await fastify.inject({
method: 'GET',
url: '/users',
});
expect(response.statusCode).toBe(200);
const body = JSON.parse(response.body) as PaginatedResponse<UserResponse>;
PaginatedUsersSchema.parse(body); // Zod validation
});
});fastify.inject() is purpose-built for tests — no network, no ports, and it returns the full response object with typed methods.
CI Configuration
Run integration tests separately from unit tests to avoid database dependency in the fast feedback loop:
# .github/workflows/test.yml
jobs:
unit-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run test:unit
integration-tests:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: test
POSTGRES_DB: testdb
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run db:migrate
env:
DATABASE_URL: postgresql://postgres:test@localhost/testdb
- run: npm run test:integration
env:
DATABASE_URL: postgresql://postgres:test@localhost/testdbSeparate jest.config.unit.ts and jest.config.integration.ts files with different testMatch patterns (**/*.unit.test.ts vs **/*.integration.test.ts) keep the runs isolated.
Common Mistakes
Testing against a running server URL. supertest('http://localhost:3000') depends on an external process. Use supertest(app) instead.
Not asserting the response body type. Checking only expect(200) tells you nothing about what was returned. Assert the shape.
Sharing state between tests. Each test should be independent. Use beforeEach for setup, not beforeAll, unless the setup is read-only.
Missing await on async requests. Supertest calls return promises. Without await, the test passes before the assertion runs.
Not closing DB connections. afterAll(() => db.end()) is required, or Jest hangs with an open handle warning.
What to Test
Focus integration tests on scenarios that unit tests can't cover:
- Happy paths — the full request/response cycle with real data
- Auth enforcement — endpoints return 401/403 for missing/wrong tokens
- Validation errors — malformed request bodies return 400 with useful error messages
- Edge cases — empty lists, large pagination offsets, special characters in inputs
- Error propagation — database errors surface as 500s, not as leaked stack traces
Unit tests cover the business logic. Integration tests cover the API contract. Together they give you confidence to ship.