|
| 1 | +import { expect } from "vitest"; |
| 2 | +import { http, HttpResponse, delay } from "msw"; |
| 3 | +import { server } from "./server"; |
| 4 | + |
| 5 | +type HeaderExpectation = |
| 6 | + string | RegExp | ((value: string | undefined) => boolean); |
| 7 | +interface HttpExpectation { |
| 8 | + method: "get" | "post" | "put" | "patch" | "delete"; |
| 9 | + url: string; |
| 10 | + body?: any; |
| 11 | + inspect?: (request: Request) => void | Promise<void>; |
| 12 | + query?: |
| 13 | + | true |
| 14 | + | Record<string, unknown> |
| 15 | + | ((query: Record<string, string>) => boolean); |
| 16 | + headers?: [string, HeaderExpectation][]; |
| 17 | + reqheaders?: Record<string, HeaderExpectation>; |
| 18 | + badheaders?: string[]; |
| 19 | + times?: number; |
| 20 | + delayMs?: number; |
| 21 | + networkError?: boolean; |
| 22 | + status?: number; |
| 23 | + response?: any; |
| 24 | + responseHeaders?: Record<string, string>; |
| 25 | + respond?: (request: Request) => [number, any]; |
| 26 | +} |
| 27 | +interface Capture { |
| 28 | + request: Request; |
| 29 | + body: unknown; |
| 30 | +} |
| 31 | +const expectations: { |
| 32 | + expected: HttpExpectation; |
| 33 | + requests: Capture[]; |
| 34 | + failures: unknown[]; |
| 35 | +}[] = []; |
| 36 | + |
| 37 | +/** A native MSW handler with after-test request contract verification. |
| 38 | + * Resolver assertions cannot fail a test reliably: MSW translates exceptions |
| 39 | + * into HTTP 500 responses. Capturing them separately also covers error paths. |
| 40 | + * Repeated registrations for one route form a response sequence, in order. |
| 41 | + */ |
| 42 | +export function mockHttp(expected: HttpExpectation) { |
| 43 | + expectations.push({ expected, requests: [], failures: [] }); |
| 44 | + // Use an exact regex: operation IDs may contain MSW path-pattern metacharacters. |
| 45 | + const url = new RegExp( |
| 46 | + "^" + expected.url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "(?:\\?.*)?$", |
| 47 | + ); |
| 48 | + server.use( |
| 49 | + http[expected.method](url, async ({ request }) => { |
| 50 | + const sameRoute = expectations.filter( |
| 51 | + (item) => |
| 52 | + item.expected.method === expected.method && |
| 53 | + item.expected.url === expected.url, |
| 54 | + ); |
| 55 | + const item = |
| 56 | + sameRoute.find( |
| 57 | + (item) => item.requests.length < (item.expected.times ?? 1), |
| 58 | + ) ?? sameRoute.at(-1)!; |
| 59 | + const rule = item.expected; |
| 60 | + const text = request.body ? await request.clone().text() : ""; |
| 61 | + let body: unknown = text; |
| 62 | + if ( |
| 63 | + text && |
| 64 | + request.headers.get("content-type")?.includes("application/json") |
| 65 | + ) |
| 66 | + body = JSON.parse(text); |
| 67 | + item.requests.push({ request, body }); |
| 68 | + if (typeof rule.body === "function") { |
| 69 | + try { |
| 70 | + expect(rule.body(body)).toBe(true); |
| 71 | + } catch (error) { |
| 72 | + item.failures.push(error); |
| 73 | + } |
| 74 | + } |
| 75 | + if (rule.inspect) { |
| 76 | + try { |
| 77 | + await rule.inspect(request.clone()); |
| 78 | + } catch (error) { |
| 79 | + item.failures.push(error); |
| 80 | + } |
| 81 | + } |
| 82 | + if (rule.delayMs) await delay(rule.delayMs); |
| 83 | + if (rule.networkError) return HttpResponse.error(); |
| 84 | + const [status, response] = rule.respond?.(request) ?? [ |
| 85 | + rule.status ?? 200, |
| 86 | + rule.response, |
| 87 | + ]; |
| 88 | + const init = { status, headers: rule.responseHeaders }; |
| 89 | + return typeof response === "string" |
| 90 | + ? new HttpResponse(response, init) |
| 91 | + : HttpResponse.json(response, init); |
| 92 | + }), |
| 93 | + ); |
| 94 | +} |
| 95 | + |
| 96 | +export function verifyHttpExpectations() { |
| 97 | + const pending = expectations.splice(0); |
| 98 | + for (const { expected, requests, failures } of pending) { |
| 99 | + if (failures.length) throw failures[0]; |
| 100 | + expect( |
| 101 | + requests, |
| 102 | + `${expected.method.toUpperCase()} ${expected.url} request count`, |
| 103 | + ).toHaveLength(expected.times ?? 1); |
| 104 | + for (const { request, body } of requests) { |
| 105 | + if ("body" in expected && typeof expected.body !== "function") |
| 106 | + expect(body).toEqual(expected.body); |
| 107 | + if (expected.query && expected.query !== true) { |
| 108 | + const query = Object.fromEntries(new URL(request.url).searchParams); |
| 109 | + if (typeof expected.query === "function") |
| 110 | + expect(expected.query(query)).toBe(true); |
| 111 | + else expect(query).toEqual(expected.query); |
| 112 | + } |
| 113 | + for (const [name, value] of [ |
| 114 | + ...Object.entries(expected.reqheaders ?? {}), |
| 115 | + ...(expected.headers ?? []), |
| 116 | + ]) { |
| 117 | + const actual = request.headers.get(name) ?? undefined; |
| 118 | + if (typeof value === "function") expect(value(actual)).toBe(true); |
| 119 | + else if (value instanceof RegExp) expect(actual).toMatch(value); |
| 120 | + else expect(actual, `header ${name}`).toBe(value); |
| 121 | + } |
| 122 | + for (const name of expected.badheaders ?? []) |
| 123 | + expect(request.headers.has(name), `absent header ${name}`).toBe(false); |
| 124 | + } |
| 125 | + } |
| 126 | +} |
0 commit comments