import express, { Express, NextFunction, Request, Response } from 'express';
import { userRoutes } from './userRoutes';
function authenticate(req: Request, res: Response, next: NextFunction) {
const header = req.header('authorization');
if (!header || !header.startsWith('Bearer ')) {
return res.status(401).json({ error: 'missing token' });
}
const token = header.slice('Bearer '.length);
if (token !== 'valid-token') {
return res.status(401).json({ error: 'invalid token' });
}
req.user = { id: '42', role: 'member' };
next();
}
export function createApp(): Express {
const app = express();
app.use(express.json());
app.use(authenticate);
app.use('/users', userRoutes);
return app;
}
import { Router, Request, Response } from 'express';
import { userService } from './userService';
export const userRoutes = Router();
userRoutes.get('/:id', async (req: Request, res: Response) => {
const caller = req.user;
if (!caller) {
return res.status(401).json({ error: 'unauthenticated' });
}
if (caller.id !== req.params.id && caller.role !== 'admin') {
return res.status(403).json({ error: 'forbidden' });
}
const user = await userService.findById(req.params.id);
if (!user) {
return res.status(404).json({ error: 'not found' });
}
return res.status(200).json(user);
});
import { createApp } from './app';
const port = Number(process.env.PORT ?? 3000);
const app = createApp();
app.listen(port, () => {
console.log(`listening on :${port}`);
});
import request from 'supertest';
import { createApp } from './app';
import { userService } from './userService';
jest.mock('./userService');
const mockedFindById = userService.findById as jest.MockedFunction<typeof userService.findById>;
const app = createApp();
const auth = 'Bearer valid-token';
describe('GET /users/:id', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('returns 401 without a token', async () => {
await request(app).get('/users/42').expect(401);
expect(mockedFindById).not.toHaveBeenCalled();
});
it('returns the user for the authenticated caller', async () => {
mockedFindById.mockResolvedValue({ id: '42', name: 'Ada' });
const res = await request(app)
.get('/users/42')
.set('Authorization', auth)
.expect('Content-Type', /json/)
.expect(200);
expect(res.body).toEqual({ id: '42', name: 'Ada' });
expect(mockedFindById).toHaveBeenCalledWith('42');
});
it('returns 403 when requesting another user', async () => {
await request(app).get('/users/99').set('Authorization', auth).expect(403);
expect(mockedFindById).not.toHaveBeenCalled();
});
it('returns 404 when the service finds nothing', async () => {
mockedFindById.mockResolvedValue(null);
await request(app).get('/users/42').set('Authorization', auth).expect(404);
});
});
This snippet shows how an Express API is wired so its HTTP routes can be tested end-to-end with Supertest and Jest without spinning up a real network listener. The central idea is to separate the Express app from the process that binds it to a port. Supertest can take a bare app object and drive requests through it in-process, which makes tests fast, deterministic, and free of port collisions.
In app.ts the createApp factory returns a configured express() instance without ever calling listen. It mounts express.json(), an auth middleware, and a small /users router. Keeping construction in a factory means each test can build a fresh app, and it also isolates the app from server.ts, which is the only file that actually opens a socket. That split is the key trick for testable HTTP services.
userRoutes.ts defines the behavior under test. The GET /users/:id handler validates that req.user was populated by the auth layer, returns 403 when the caller asks for another user's record, and delegates to a userService that the tests will stub. Because the route depends on an injected-looking module rather than a live database, the test can control its return value and assert on both success and failure paths.
users.test.ts is the integration test. It uses jest.mock to replace the userService module so no real datastore is touched, and beforeEach resets mocks to prevent state leaking between cases. Each test calls request(app) from Supertest, sets an Authorization header, and chains .expect(...) assertions on status and body. The 403 case demonstrates testing an error branch by requesting a mismatched id, and the 404 case drives the stubbed service to return null.
The trade-off is that in-process tests exercise the full middleware stack and routing but not the real HTTP server or network, so a thin smoke test against server.ts is still worthwhile. Common pitfalls this structure avoids are leaking listeners between suites and forgetting to reset mocks. Reaching for this pattern is appropriate whenever route logic, middleware, and status codes need fast, reliable coverage.
Related snips
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
import axios, { AxiosError } from 'axios'
import { v4 as uuidv4 } from 'uuid'
const api = axios.create({
baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000/api/v1',
timeout: 15000,
Axios API client with interceptors
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface FilterState {
search: string
category: string | null
Zustand for lightweight state management
import { randomBytes, createHash } from "crypto";
import jwt from "jsonwebtoken";
import { RefreshTokenStore } from "./store";
const ACCESS_SECRET = process.env.ACCESS_SECRET!;
const ACCESS_TTL = "15m";
JWT access + refresh token rotation (conceptual)
Share this code
Here's the card — post it anywhere.