|
| 1 | +import { |
| 2 | + correlationMiddleware, |
| 3 | + getCorrelationId, |
| 4 | + injectCorrelationIdToHeaders, |
| 5 | + CORRELATION_ID_HEADER, |
| 6 | +} from './correlation.utils'; |
| 7 | + |
| 8 | +describe('correlation.utils', () => { |
| 9 | + it('generates and propagates correlation ID through middleware', (done) => { |
| 10 | + const req: any = { method: 'GET', url: '/test', headers: {} }; |
| 11 | + const headers: Record<string, string> = {}; |
| 12 | + const res: any = { |
| 13 | + setHeader: (name: string, value: string) => { |
| 14 | + headers[name.toLowerCase()] = value; |
| 15 | + }, |
| 16 | + getHeader: (name: string) => headers[name.toLowerCase()], |
| 17 | + }; |
| 18 | + |
| 19 | + correlationMiddleware(req, res, () => { |
| 20 | + const id = getCorrelationId(); |
| 21 | + expect(typeof id).toBe('string'); |
| 22 | + expect(res.getHeader(CORRELATION_ID_HEADER)).toBe(id); |
| 23 | + done(); |
| 24 | + }); |
| 25 | + }); |
| 26 | + |
| 27 | + it('respects incoming x-request-id header', (done) => { |
| 28 | + const incomingId = 'test-correlation-id'; |
| 29 | + const req: any = { method: 'GET', url: '/test', headers: { 'x-request-id': incomingId } }; |
| 30 | + const headers: Record<string, string> = {}; |
| 31 | + const res: any = { |
| 32 | + setHeader: (name: string, value: string) => { |
| 33 | + headers[name.toLowerCase()] = value; |
| 34 | + }, |
| 35 | + getHeader: (name: string) => headers[name.toLowerCase()], |
| 36 | + }; |
| 37 | + |
| 38 | + correlationMiddleware(req, res, () => { |
| 39 | + expect(getCorrelationId()).toBe(incomingId); |
| 40 | + expect(res.getHeader(CORRELATION_ID_HEADER)).toBe(incomingId); |
| 41 | + done(); |
| 42 | + }); |
| 43 | + }); |
| 44 | + |
| 45 | + it('injects correlation header into outgoing request headers', () => { |
| 46 | + const custom = injectCorrelationIdToHeaders({ Authorization: 'Bearer token' }, 'cid-1'); |
| 47 | + expect(custom[CORRELATION_ID_HEADER]).toBe('cid-1'); |
| 48 | + expect(custom.Authorization).toBe('Bearer token'); |
| 49 | + }); |
| 50 | +}); |
0 commit comments