|
| 1 | +/** |
| 2 | + * Integration tests for errorHandlerMiddleware (issue #341) |
| 3 | + * |
| 4 | + * Verifies that every error path produces a response matching the standard |
| 5 | + * shape: { code: string, message: string, details: unknown[] } |
| 6 | + */ |
| 7 | + |
| 8 | +import express, { Request, Response, NextFunction } from 'express'; |
| 9 | +import request from 'supertest'; |
| 10 | +import { ZodError, z } from 'zod'; |
| 11 | +import { errorHandlerMiddleware, HttpError } from '../middlewares/errorHandlerMiddleware.js'; |
| 12 | +import { ErrorCodes } from '../utils/apiError.js'; |
| 13 | + |
| 14 | +// ── Test app factory ────────────────────────────────────────────────────────── |
| 15 | + |
| 16 | +function makeApp(thrower: (req: Request, res: Response, next: NextFunction) => void) { |
| 17 | + const app = express(); |
| 18 | + app.use(express.json()); |
| 19 | + |
| 20 | + // Attach a requestId for the middleware to include in responses |
| 21 | + app.use((req: Request, _res: Response, next: NextFunction) => { |
| 22 | + req.requestId = 'test-req-id'; |
| 23 | + next(); |
| 24 | + }); |
| 25 | + |
| 26 | + app.get('/test', thrower); |
| 27 | + app.use(errorHandlerMiddleware); |
| 28 | + return app; |
| 29 | +} |
| 30 | + |
| 31 | +// ── Helpers ─────────────────────────────────────────────────────────────────── |
| 32 | + |
| 33 | +function assertStandardShape(body: Record<string, unknown>) { |
| 34 | + expect(typeof body.code).toBe('string'); |
| 35 | + expect(typeof body.message).toBe('string'); |
| 36 | + expect(Array.isArray(body.details)).toBe(true); |
| 37 | +} |
| 38 | + |
| 39 | +// ── ZodError ────────────────────────────────────────────────────────────────── |
| 40 | + |
| 41 | +describe('errorHandlerMiddleware — ZodError', () => { |
| 42 | + it('returns 400 with VALIDATION_ERROR code and issue details', async () => { |
| 43 | + const app = makeApp((_req, _res, next) => { |
| 44 | + const schema = z.object({ email: z.string().email() }); |
| 45 | + try { |
| 46 | + schema.parse({ email: 'not-an-email' }); |
| 47 | + } catch (err) { |
| 48 | + next(err); |
| 49 | + } |
| 50 | + }); |
| 51 | + |
| 52 | + const res = await request(app).get('/test'); |
| 53 | + |
| 54 | + expect(res.status).toBe(400); |
| 55 | + assertStandardShape(res.body); |
| 56 | + expect(res.body.code).toBe(ErrorCodes.VALIDATION_ERROR); |
| 57 | + expect(res.body.details.length).toBeGreaterThan(0); |
| 58 | + expect(res.body.details[0]).toHaveProperty('path'); |
| 59 | + expect(res.body.details[0]).toHaveProperty('message'); |
| 60 | + }); |
| 61 | +}); |
| 62 | + |
| 63 | +// ── HTTP-tagged errors ──────────────────────────────────────────────────────── |
| 64 | + |
| 65 | +describe('errorHandlerMiddleware — HttpError', () => { |
| 66 | + it.each([ |
| 67 | + [400, ErrorCodes.BAD_REQUEST, 'Bad input'], |
| 68 | + [401, ErrorCodes.UNAUTHORIZED, 'Token missing'], |
| 69 | + [403, ErrorCodes.FORBIDDEN, 'Access denied'], |
| 70 | + [404, ErrorCodes.NOT_FOUND, 'Not found'], |
| 71 | + [409, ErrorCodes.CONFLICT, 'Already exists'], |
| 72 | + [422, ErrorCodes.UNPROCESSABLE, 'Unprocessable'], |
| 73 | + [429, ErrorCodes.RATE_LIMITED, 'Too many requests'], |
| 74 | + ])('status %d → code %s', async (status, expectedCode, message) => { |
| 75 | + const app = makeApp((_req, _res, next) => { |
| 76 | + const err: HttpError = Object.assign(new Error(message), { status }); |
| 77 | + next(err); |
| 78 | + }); |
| 79 | + |
| 80 | + const res = await request(app).get('/test'); |
| 81 | + |
| 82 | + expect(res.status).toBe(status); |
| 83 | + assertStandardShape(res.body); |
| 84 | + expect(res.body.code).toBe(expectedCode); |
| 85 | + expect(res.body.message).toBe(message); |
| 86 | + }); |
| 87 | + |
| 88 | + it('uses the error code field when provided', async () => { |
| 89 | + const app = makeApp((_req, _res, next) => { |
| 90 | + const err: HttpError = Object.assign(new Error('Custom'), { |
| 91 | + status: 400, |
| 92 | + code: 'CUSTOM_CODE', |
| 93 | + }); |
| 94 | + next(err); |
| 95 | + }); |
| 96 | + |
| 97 | + const res = await request(app).get('/test'); |
| 98 | + expect(res.body.code).toBe('CUSTOM_CODE'); |
| 99 | + }); |
| 100 | + |
| 101 | + it('includes details array from the error when provided', async () => { |
| 102 | + const app = makeApp((_req, _res, next) => { |
| 103 | + const err: HttpError = Object.assign(new Error('With details'), { |
| 104 | + status: 422, |
| 105 | + details: [{ field: 'email', message: 'Invalid format' }], |
| 106 | + }); |
| 107 | + next(err); |
| 108 | + }); |
| 109 | + |
| 110 | + const res = await request(app).get('/test'); |
| 111 | + expect(res.body.details).toHaveLength(1); |
| 112 | + expect(res.body.details[0]).toHaveProperty('field', 'email'); |
| 113 | + }); |
| 114 | +}); |
| 115 | + |
| 116 | +// ── Client-side JS errors ───────────────────────────────────────────────────── |
| 117 | + |
| 118 | +describe('errorHandlerMiddleware — client JS errors', () => { |
| 119 | + it.each([ |
| 120 | + ['TypeError', new TypeError('invalid type')], |
| 121 | + ['RangeError', new RangeError('out of range')], |
| 122 | + ['SyntaxError', new SyntaxError('bad syntax')], |
| 123 | + ])('%s → 400 BAD_REQUEST', async (_label, err) => { |
| 124 | + const app = makeApp((_req, _res, next) => next(err)); |
| 125 | + |
| 126 | + const res = await request(app).get('/test'); |
| 127 | + |
| 128 | + expect(res.status).toBe(400); |
| 129 | + assertStandardShape(res.body); |
| 130 | + expect(res.body.code).toBe(ErrorCodes.BAD_REQUEST); |
| 131 | + }); |
| 132 | +}); |
| 133 | + |
| 134 | +// ── Unhandled / internal errors ─────────────────────────────────────────────── |
| 135 | + |
| 136 | +describe('errorHandlerMiddleware — unhandled errors', () => { |
| 137 | + const originalEnv = process.env.NODE_ENV; |
| 138 | + |
| 139 | + afterEach(() => { |
| 140 | + process.env.NODE_ENV = originalEnv; |
| 141 | + }); |
| 142 | + |
| 143 | + it('returns 500 INTERNAL_ERROR', async () => { |
| 144 | + const app = makeApp((_req, _res, next) => { |
| 145 | + next(new Error('Something exploded')); |
| 146 | + }); |
| 147 | + |
| 148 | + const res = await request(app).get('/test'); |
| 149 | + |
| 150 | + expect(res.status).toBe(500); |
| 151 | + assertStandardShape(res.body); |
| 152 | + expect(res.body.code).toBe(ErrorCodes.INTERNAL_ERROR); |
| 153 | + }); |
| 154 | + |
| 155 | + it('hides the real message in production', async () => { |
| 156 | + process.env.NODE_ENV = 'production'; |
| 157 | + |
| 158 | + const app = makeApp((_req, _res, next) => { |
| 159 | + next(new Error('Secret internal detail')); |
| 160 | + }); |
| 161 | + |
| 162 | + const res = await request(app).get('/test'); |
| 163 | + |
| 164 | + expect(res.status).toBe(500); |
| 165 | + expect(res.body.message).not.toContain('Secret internal detail'); |
| 166 | + expect(res.body.message).toBe('An unexpected error occurred'); |
| 167 | + }); |
| 168 | + |
| 169 | + it('exposes the message in development', async () => { |
| 170 | + process.env.NODE_ENV = 'development'; |
| 171 | + |
| 172 | + const app = makeApp((_req, _res, next) => { |
| 173 | + next(new Error('Dev detail')); |
| 174 | + }); |
| 175 | + |
| 176 | + const res = await request(app).get('/test'); |
| 177 | + |
| 178 | + expect(res.status).toBe(500); |
| 179 | + expect(res.body.message).toBe('Dev detail'); |
| 180 | + }); |
| 181 | + |
| 182 | + it('handles non-Error thrown values', async () => { |
| 183 | + const app = makeApp((_req, _res, next) => { |
| 184 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 185 | + next('a plain string error' as any); |
| 186 | + }); |
| 187 | + |
| 188 | + const res = await request(app).get('/test'); |
| 189 | + |
| 190 | + expect(res.status).toBe(500); |
| 191 | + assertStandardShape(res.body); |
| 192 | + }); |
| 193 | +}); |
| 194 | + |
| 195 | +// ── Standard shape on success ───────────────────────────────────────────────── |
| 196 | + |
| 197 | +describe('errorHandlerMiddleware — shape compliance', () => { |
| 198 | + it('every error response has code, message, and details fields', async () => { |
| 199 | + const errors: Error[] = [ |
| 200 | + new Error('generic'), |
| 201 | + Object.assign(new Error('not found'), { status: 404 }), |
| 202 | + Object.assign(new Error('rate limited'), { status: 429 }), |
| 203 | + ]; |
| 204 | + |
| 205 | + for (const err of errors) { |
| 206 | + const app = makeApp((_req, _res, next) => next(err)); |
| 207 | + const res = await request(app).get('/test'); |
| 208 | + |
| 209 | + expect(res.body).toHaveProperty('code'); |
| 210 | + expect(res.body).toHaveProperty('message'); |
| 211 | + expect(res.body).toHaveProperty('details'); |
| 212 | + expect(Array.isArray(res.body.details)).toBe(true); |
| 213 | + } |
| 214 | + }); |
| 215 | +}); |
0 commit comments