|
| 1 | +import type {AxiosResponse} from 'axios'; |
| 2 | + |
| 3 | +import axios from 'axios'; |
| 4 | +import MockAdapter from 'axios-mock-adapter'; |
| 5 | +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; |
| 6 | + |
| 7 | +import type {ResponseMiddlewareFunc} from '../src/types'; |
| 8 | + |
| 9 | +import {createHttpService} from '../src/index'; |
| 10 | + |
| 11 | +// Contract pins for the fs-http middleware mechanism. Each test locks one |
| 12 | +// documented invariant (README §Middleware contract / the register* JSDoc) so a |
| 13 | +// future regression fails CI rather than silently drifting. Written against |
| 14 | +// fs-http 0.6.0 (guard-by-default, ADR-0037): throw-isolation itself is pinned |
| 15 | +// in http.spec.ts §"middleware guarding by default"; this file pins the |
| 16 | +// invariants that survive UNCHANGED across ADR-0037 — ordering, per-instance |
| 17 | +// scoping, non-idempotency, mutation visibility, response-object freshness, and |
| 18 | +// the sync-only / fire-and-forget execution shape (including the one gap |
| 19 | +// guard-by-default does NOT close: async rejections). |
| 20 | + |
| 21 | +const BASE_URL = 'https://api.example.com'; |
| 22 | + |
| 23 | +let mock: MockAdapter; |
| 24 | + |
| 25 | +beforeEach(() => { |
| 26 | + mock = new MockAdapter(axios); |
| 27 | + mock.onGet(/.*/).reply(200, {ok: true}); |
| 28 | +}); |
| 29 | + |
| 30 | +afterEach(() => { |
| 31 | + mock.restore(); |
| 32 | +}); |
| 33 | + |
| 34 | +describe('fs-http middleware contract', () => { |
| 35 | + describe('ordering', () => { |
| 36 | + it('runs response middleware in FIFO registration order', async () => { |
| 37 | + // Arrange |
| 38 | + const service = createHttpService(BASE_URL); |
| 39 | + const order: number[] = []; |
| 40 | + service.registerResponseMiddleware(() => order.push(1)); |
| 41 | + service.registerResponseMiddleware(() => order.push(2)); |
| 42 | + service.registerResponseMiddleware(() => order.push(3)); |
| 43 | + |
| 44 | + // Act |
| 45 | + await service.getRequest('/test'); |
| 46 | + |
| 47 | + // Assert — insertion order preserved on the response path (request path |
| 48 | + // is pinned in http.spec.ts; both share the same iteration shape). |
| 49 | + expect(order).toEqual([1, 2, 3]); |
| 50 | + }); |
| 51 | + }); |
| 52 | + |
| 53 | + describe('per-instance scoping', () => { |
| 54 | + it('scopes middleware to the service instance it was registered on', async () => { |
| 55 | + // Arrange — two independent services; middleware only on A. |
| 56 | + const serviceA = createHttpService(BASE_URL); |
| 57 | + const serviceB = createHttpService(BASE_URL); |
| 58 | + const onA = vi.fn(); |
| 59 | + serviceA.registerResponseMiddleware(onA); |
| 60 | + |
| 61 | + // Act — a request through B must not touch A's stack. |
| 62 | + await serviceB.getRequest('/test'); |
| 63 | + |
| 64 | + // Assert |
| 65 | + expect(onA).not.toHaveBeenCalled(); |
| 66 | + |
| 67 | + // Act — a request through A does fire A's middleware. |
| 68 | + await serviceA.getRequest('/test'); |
| 69 | + |
| 70 | + // Assert |
| 71 | + expect(onA).toHaveBeenCalledTimes(1); |
| 72 | + }); |
| 73 | + }); |
| 74 | + |
| 75 | + describe('non-idempotent registration', () => { |
| 76 | + it('fires a body once per registration — the same reference registered twice fires twice', async () => { |
| 77 | + // Arrange — each register* call wraps fn in a fresh guarded() wrapper, |
| 78 | + // so both registrations are live and both invoke fn. |
| 79 | + const service = createHttpService(BASE_URL); |
| 80 | + const fn = vi.fn(); |
| 81 | + const unregisterFirst = service.registerResponseMiddleware(fn); |
| 82 | + service.registerResponseMiddleware(fn); |
| 83 | + |
| 84 | + // Act |
| 85 | + await service.getRequest('/first'); |
| 86 | + |
| 87 | + // Assert — not deduped: two registrations => two calls. |
| 88 | + expect(fn).toHaveBeenCalledTimes(2); |
| 89 | + |
| 90 | + // Act — one unregister removes only its own copy; the other stays live. |
| 91 | + unregisterFirst(); |
| 92 | + fn.mockClear(); |
| 93 | + await service.getRequest('/second'); |
| 94 | + |
| 95 | + // Assert |
| 96 | + expect(fn).toHaveBeenCalledTimes(1); |
| 97 | + }); |
| 98 | + }); |
| 99 | + |
| 100 | + describe('mutation semantics', () => { |
| 101 | + it('makes a mutation from one middleware visible to a later middleware on the same response', async () => { |
| 102 | + // Arrange — same response object is threaded through the whole chain. |
| 103 | + const service = createHttpService(BASE_URL); |
| 104 | + let sawInjected: string | undefined; |
| 105 | + service.registerResponseMiddleware((response) => { |
| 106 | + (response as AxiosResponse & {injected?: string}).injected = 'from-A'; |
| 107 | + }); |
| 108 | + service.registerResponseMiddleware((response) => { |
| 109 | + sawInjected = (response as AxiosResponse & {injected?: string}).injected; |
| 110 | + }); |
| 111 | + |
| 112 | + // Act |
| 113 | + await service.getRequest('/test'); |
| 114 | + |
| 115 | + // Assert |
| 116 | + expect(sawInjected).toBe('from-A'); |
| 117 | + }); |
| 118 | + |
| 119 | + it('does not reuse the response object across responses — a mutation does not bleed into the next request', async () => { |
| 120 | + // Arrange |
| 121 | + const service = createHttpService(BASE_URL); |
| 122 | + const seen: AxiosResponse[] = []; |
| 123 | + service.registerResponseMiddleware((response) => { |
| 124 | + (response as AxiosResponse & {marked?: boolean}).marked = true; |
| 125 | + seen.push(response); |
| 126 | + }); |
| 127 | + |
| 128 | + // Act |
| 129 | + await service.getRequest('/first'); |
| 130 | + await service.getRequest('/second'); |
| 131 | + |
| 132 | + // Assert — axios hands back a fresh response object per request. |
| 133 | + expect(seen).toHaveLength(2); |
| 134 | + expect(seen[0]).not.toBe(seen[1]); |
| 135 | + }); |
| 136 | + }); |
| 137 | + |
| 138 | + describe('execution timing (sync-only, fire-and-forget)', () => { |
| 139 | + it('completes the synchronous middleware loop before the caller await resumes', async () => { |
| 140 | + // Arrange |
| 141 | + const service = createHttpService(BASE_URL); |
| 142 | + let ranDuringLoop = false; |
| 143 | + service.registerResponseMiddleware(() => { |
| 144 | + ranDuringLoop = true; |
| 145 | + }); |
| 146 | + |
| 147 | + // Act |
| 148 | + const response = await service.getRequest('/test'); |
| 149 | + |
| 150 | + // Assert — by the time the caller resumes, the loop has run to completion. |
| 151 | + expect(ranDuringLoop).toBe(true); |
| 152 | + expect(response.status).toBe(200); |
| 153 | + }); |
| 154 | + |
| 155 | + it('does not await an async middleware body — a never-resolving body does not block response delivery', async () => { |
| 156 | + // Arrange — a body that returns a forever-pending promise. If the |
| 157 | + // interceptor awaited middleware, getRequest would hang; it resolves |
| 158 | + // because the loop is fire-and-forget. The promise never rejects, so |
| 159 | + // there is no unhandled rejection. |
| 160 | + const service = createHttpService(BASE_URL); |
| 161 | + const neverResolves: ResponseMiddlewareFunc = () => new Promise<void>(() => {}); |
| 162 | + service.registerResponseMiddleware(neverResolves); |
| 163 | + |
| 164 | + // Act |
| 165 | + const response = await service.getRequest('/test'); |
| 166 | + |
| 167 | + // Assert |
| 168 | + expect(response.status).toBe(200); |
| 169 | + }); |
| 170 | + |
| 171 | + it('does NOT catch an async rejection — guard-by-default is sync-only; the request still resolves', async () => { |
| 172 | + // Arrange — models an `async () => { throw }` body's rejected RETURN. |
| 173 | + // guarded()'s try/catch is synchronous, so it never observes this |
| 174 | + // rejection: onMiddlewareError does not fire and the request resolves. |
| 175 | + // The rejection is pre-handled so the test runner never sees a floating |
| 176 | + // unhandled rejection — this is a leak-safe stand-in for the real |
| 177 | + // async body, not a suppression of the behavior under test. |
| 178 | + const onMiddlewareError = vi.fn(); |
| 179 | + const service = createHttpService(BASE_URL, {onMiddlewareError}); |
| 180 | + const rejected = Promise.reject(new Error('async middleware boom')); |
| 181 | + rejected.catch(() => {}); |
| 182 | + const asyncRejecting: ResponseMiddlewareFunc = () => rejected; |
| 183 | + service.registerResponseMiddleware(asyncRejecting); |
| 184 | + |
| 185 | + // Act |
| 186 | + const response = await service.getRequest('/test'); |
| 187 | + |
| 188 | + // Assert — the async rejection is invisible to guard-by-default. |
| 189 | + expect(response.status).toBe(200); |
| 190 | + expect(onMiddlewareError).not.toHaveBeenCalled(); |
| 191 | + }); |
| 192 | + }); |
| 193 | +}); |
0 commit comments