import express from 'express'; import request from 'supertest'; import { z } from 'zod'; // 1.52.1: the API document describes every route. Routes answered by a v1 handler carry // `documented` shapes — in the document, never enforced, and logged outside production when the // real body or answer doesn't fit them. jest.mock('../src/middleware/authMiddleware', () => ({ protect: (_req: unknown, _res: unknown, next: () => void) => next(), optionalAuth: (_req: unknown, _res: unknown, next: () => void) => next(), admin: (_req: unknown, _res: unknown, next: () => void) => next(), staff: (_req: unknown, _res: unknown, next: () => void) => next(), supervisor: (_req: unknown, _res: unknown, next: () => void) => next(), loginLimiter: (_req: unknown, _res: unknown, next: () => void) => next(), })); import { defineRoute, mount } from '../src/v2/route'; import { buildOpenApi } from '../src/v2/openapi'; import { errorHandler } from '../src/v2/errors'; const documented = defineRoute({ method: 'post', path: '/docs-test/things', tag: 'Test', summary: 'Make a thing', access: 'public', body: z.looseObject({}), response: z.object({ data: z.unknown() }), documented: { body: z.object({ name: z.string() }), response: z.object({ id: z.string(), name: z.string() }) }, handler: ({ req }) => ({ data: (req.body as { name?: unknown }).name === 'odd' ? { id: 1 } : { id: 't1', name: String((req.body as { name?: unknown }).name) } }), }); const action = defineRoute({ method: 'post', path: '/docs-test/things/:id/poke', tag: 'Test', summary: 'Poke a thing', access: 'public', params: z.object({ id: z.string() }), query: z.looseObject({ from: z.string().optional() }), body: z.looseObject({}), response: z.object({ data: z.unknown() }), handler: () => ({ data: null }), }); const app = express(); app.use(express.json()); const router = express.Router(); mount(router, [documented, action]); router.use(errorHandler); app.use('/api/v2', router); describe('documented shapes', () => { const doc = buildOpenApi({ version: 'test', list: [documented, action] }) as any; const op = doc.paths['/docs-test/things'].post; test('are what the document shows, in place of the generic body and answer', () => { expect(op.requestBody.required).toBe(true); expect(op.requestBody.content['application/json'].schema.properties.name).toEqual({ type: 'string' }); expect(op.responses['200'].content['application/json'].schema.properties.data.properties).toEqual({ id: { type: 'string' }, name: { type: 'string' } }); }); test('an action with no input says it needs no body; parameters get their common description', () => { const poke = doc.paths['/docs-test/things/{id}/poke'].post; expect(poke.requestBody).toMatchObject({ required: true, description: expect.stringContaining('No body needed') }); expect(poke.parameters).toEqual(expect.arrayContaining([ expect.objectContaining({ name: 'id', in: 'path', description: 'The id' }), expect.objectContaining({ name: 'from', in: 'query', description: expect.stringContaining('On or after') }), ])); }); test('are never enforced: a body or answer that doesn\'t fit still goes through, and is logged', async () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); const fits = await request(app).post('/api/v2/docs-test/things').send({ name: 'Bob' }); expect(fits.status).toBe(200); expect(warn).not.toHaveBeenCalled(); const odd = await request(app).post('/api/v2/docs-test/things').send({ name: 'odd' }); expect(odd.status).toBe(200); expect(odd.body).toEqual({ data: { id: 1 } }); const noName = await request(app).post('/api/v2/docs-test/things').send({}); expect(noName.status).toBe(200); expect(warn.mock.calls.map(c => c[0])).toEqual([ expect.stringContaining('answer doesn\'t match its documented schema'), expect.stringContaining('request body doesn\'t match its documented schema'), ]); warn.mockRestore(); }); }); describe('the whole API document', () => { // eslint-disable-next-line @typescript-eslint/no-require-imports require('../src/v2'); const doc = buildOpenApi({ version: 'test' }) as any; // (Leaving out this file's own test routes.) const ops = Object.entries(doc.paths).filter(([path]) => !path.startsWith('/docs-test')).flatMap(([path, methods]) => Object.entries(methods).map(([method, op]) => ({ path, method, op }))); const isBlank = (s: any) => !s || Object.keys(s).length === 0 || (s.type === 'object' && !s.properties && !s.additionalProperties && !s.description); test('every JSON answer says what\'s in it', () => { const blank = ops.filter(({ op }) => { const json = Object.entries(op.responses).find(([code]) => code.startsWith('2'))?.[1]?.content?.['application/json']; if (!json) return false; const data = json.schema?.properties?.data; return isBlank(data) || (data?.type === 'array' && isBlank(data.items)); }).map(({ method, path }) => `${method.toUpperCase()} ${path}`); // A JSON file download (my data) is the one answer that's a file, not a shape. expect(blank).toEqual(['GET /me/privacy/export']); }); test('every body that takes something says what, and every parameter is described', () => { const undescribed = ops.flatMap(({ method, path, op }) => op.parameters.filter((p: any) => !p.description).map((p: any) => `${method} ${path} ${p.in}:${p.name}`)); expect(undescribed).toEqual([]); const bodies = ops.filter(({ op }) => op.requestBody?.content?.['application/json']); for (const { op } of bodies) { const schema = op.requestBody.content['application/json'].schema; const takesSomething = (!!schema.properties && Object.keys(schema.properties).length > 0) || !!schema.additionalProperties?.type || !!schema.description; if (!takesSomething) expect(op.requestBody.description).toMatch(/No body needed/); } }); });