|
| 1 | +import { describe, expect, it } from "vitest" |
| 2 | +import { createMisina } from "../src/index.ts" |
| 3 | +import mockDriverFactory, { getMockApi } from "../src/driver/mock.ts" |
| 4 | + |
| 5 | +function jsonResponse(body: unknown): Response { |
| 6 | + return new Response(JSON.stringify(body), { |
| 7 | + headers: { "content-type": "application/json" }, |
| 8 | + }) |
| 9 | +} |
| 10 | + |
| 11 | +describe("init hook — per-request isolation (ky #861)", () => { |
| 12 | + it("mutating headers in init does not leak to a sibling concurrent request", async () => { |
| 13 | + const driver = mockDriverFactory({ response: jsonResponse({}) }) |
| 14 | + |
| 15 | + let counter = 0 |
| 16 | + const m = createMisina({ |
| 17 | + driver, |
| 18 | + retry: 0, |
| 19 | + hooks: { |
| 20 | + init: (options) => { |
| 21 | + // Each request increments and writes its own value. If options |
| 22 | + // were shared, both requests would see the same final value. |
| 23 | + counter++ |
| 24 | + options.headers["x-counter"] = String(counter) |
| 25 | + }, |
| 26 | + }, |
| 27 | + }) |
| 28 | + |
| 29 | + await Promise.all([m.get("https://api.test/a"), m.get("https://api.test/b")]) |
| 30 | + |
| 31 | + const calls = getMockApi(driver)?.calls |
| 32 | + expect(calls).toHaveLength(2) |
| 33 | + const counterA = calls?.[0]?.headers["x-counter"] |
| 34 | + const counterB = calls?.[1]?.headers["x-counter"] |
| 35 | + // Each request gets its own value; they shouldn't be identical and |
| 36 | + // should be 1 and 2 in some order. |
| 37 | + expect(new Set([counterA, counterB])).toEqual(new Set(["1", "2"])) |
| 38 | + }) |
| 39 | + |
| 40 | + it("mutating defaults.headers from init does not affect future requests", async () => { |
| 41 | + const driver = mockDriverFactory({ response: jsonResponse({}) }) |
| 42 | + |
| 43 | + const m = createMisina({ |
| 44 | + driver, |
| 45 | + retry: 0, |
| 46 | + headers: { "x-base": "first" }, |
| 47 | + hooks: { |
| 48 | + init: (options) => { |
| 49 | + // If options.headers shared the defaults reference, this would |
| 50 | + // mutate the *defaults* and persist across calls. |
| 51 | + options.headers["x-base"] = "mutated" |
| 52 | + }, |
| 53 | + }, |
| 54 | + }) |
| 55 | + |
| 56 | + await m.get("https://api.test/") |
| 57 | + await m.get("https://api.test/") |
| 58 | + |
| 59 | + const calls = getMockApi(driver)?.calls |
| 60 | + // Both requests see 'mutated' because init runs each time, but the |
| 61 | + // mutation should NOT compound (e.g. become 'mutatedmutated'). |
| 62 | + expect(calls?.[0]?.headers["x-base"]).toBe("mutated") |
| 63 | + expect(calls?.[1]?.headers["x-base"]).toBe("mutated") |
| 64 | + }) |
| 65 | +}) |
0 commit comments