|
| 1 | +import { strict as assert } from 'assert'; |
| 2 | +import { schemaVersionMiddleware } from './schema-version.middleware'; |
| 3 | +import type { Request, Response, NextFunction } from 'express'; |
| 4 | +import { REQUEST_SCHEMA_VERSION, SCHEMA_VERSION_HEADER } from '../constants/schema.constants'; |
| 5 | +import { envConfig } from '../config'; |
| 6 | + |
| 7 | +// Minimal mock helpers |
| 8 | +function mockRes() { |
| 9 | + const headers: Record<string, string> = {}; |
| 10 | + return { |
| 11 | + headers, |
| 12 | + setHeader(name: string, value: string) { |
| 13 | + headers[name] = value; |
| 14 | + }, |
| 15 | + } as unknown as Response & { headers: Record<string, string> }; |
| 16 | +} |
| 17 | + |
| 18 | +function mockReq() { |
| 19 | + return {} as Request; |
| 20 | +} |
| 21 | + |
| 22 | +function run() { |
| 23 | + // sets schema version header when enabled |
| 24 | + { |
| 25 | + const res = mockRes(); |
| 26 | + let called = false; |
| 27 | + const next: NextFunction = () => { |
| 28 | + called = true; |
| 29 | + }; |
| 30 | + |
| 31 | + // Ensure it's enabled for the test |
| 32 | + const originalValue = envConfig.ENABLE_SCHEMA_VERSION_HEADER; |
| 33 | + (envConfig as any).ENABLE_SCHEMA_VERSION_HEADER = true; |
| 34 | + |
| 35 | + schemaVersionMiddleware(mockReq(), res, next); |
| 36 | + |
| 37 | + assert.equal(res.headers[SCHEMA_VERSION_HEADER], REQUEST_SCHEMA_VERSION); |
| 38 | + assert.ok(called, 'next() should be called'); |
| 39 | + |
| 40 | + // Restore |
| 41 | + (envConfig as any).ENABLE_SCHEMA_VERSION_HEADER = originalValue; |
| 42 | + } |
| 43 | + |
| 44 | + // does not set header when disabled |
| 45 | + { |
| 46 | + const res = mockRes(); |
| 47 | + let called = false; |
| 48 | + const next: NextFunction = () => { |
| 49 | + called = true; |
| 50 | + }; |
| 51 | + |
| 52 | + // Ensure it's disabled for the test |
| 53 | + const originalValue = envConfig.ENABLE_SCHEMA_VERSION_HEADER; |
| 54 | + (envConfig as any).ENABLE_SCHEMA_VERSION_HEADER = false; |
| 55 | + |
| 56 | + schemaVersionMiddleware(mockReq(), res, next); |
| 57 | + |
| 58 | + assert.ok(!(SCHEMA_VERSION_HEADER in res.headers), 'Header should not be set'); |
| 59 | + assert.ok(called, 'next() should be called'); |
| 60 | + |
| 61 | + // Restore |
| 62 | + (envConfig as any).ENABLE_SCHEMA_VERSION_HEADER = originalValue; |
| 63 | + } |
| 64 | + |
| 65 | + console.log('schema-version.middleware tests passed'); |
| 66 | +} |
| 67 | + |
| 68 | +run(); |
0 commit comments