| @@ -0,0 +1,64 @@ |
| 1 | +// The published fetch pebble, through the library's normal consumer test path: |
| 2 | +// a literal QUERY keeps its JSON through a transient retry and an auth refresh, |
| 3 | +// and stays in csrfToken's default safe set (503, then 401, then success). |
| 4 | +import { expect, test } from "bun:test"; |
| 5 | +import { authRefresh, csrfToken, retryingFetch, type FetchLike } from "@pebble/pebble/fetch"; |
| 6 | + |
| 7 | +const json = (body: unknown, status = 200) => |
| 8 | + new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); |
| 9 | + |
| 10 | +test("the fetch policies preserve and replay a literal QUERY JSON request", async () => { |
| 11 | + const url = "https://cine.example/search"; |
| 12 | + const body = JSON.stringify({ q: "pebble", page: 2 }); |
| 13 | + const answers = [json({ error: "busy" }, 503), json({ error: "expired" }, 401), json({ results: ["pebble"] })]; |
| 14 | + const calls: { url: string; method?: string; body: unknown; contentType: string | null; csrf: string | null }[] = []; |
| 15 | + const base: FetchLike = async (input, init) => { |
| 16 | + const headers = new Headers(init?.headers); |
| 17 | + calls.push({ |
| 18 | + url: String(input), |
| 19 | + method: init?.method, |
| 20 | + body: init?.body, |
| 21 | + contentType: headers.get("content-type"), |
| 22 | + csrf: headers.get("x-csrf-token"), |
| 23 | + }); |
| 24 | + return answers.shift()!; |
| 25 | + }; |
| 26 | + |
| 27 | + const doc = document.implementation.createHTMLDocument(""); |
| 28 | + const meta = doc.createElement("meta"); |
| 29 | + meta.name = "csrf-token"; |
| 30 | + meta.content = "not-for-a-safe-query"; |
| 31 | + doc.head.appendChild(meta); |
| 32 | + let refreshed = 0; |
| 33 | + const giveUps: unknown[] = []; |
| 34 | + const query = csrfToken({ doc })( |
| 35 | + authRefresh({ |
| 36 | + bounced: response => response.status === 401, |
| 37 | + refresh: async () => { |
| 38 | + refreshed++; |
| 39 | + return true; |
| 40 | + }, |
| 41 | + onGiveUp: outcome => giveUps.push(outcome), |
| 42 | + })(retryingFetch({ base, attempts: 2, backoff: 0 })), |
| 43 | + ); |
| 44 | + |
| 45 | + const response = await query(url, { |
| 46 | + method: "QUERY", |
| 47 | + headers: { "content-type": "application/json" }, |
| 48 | + body, |
| 49 | + }); |
| 50 | + |
| 51 | + expect(response.status).toBe(200); |
| 52 | + expect(await response.json()).toEqual({ results: ["pebble"] }); |
| 53 | + expect(refreshed).toBe(1); |
| 54 | + expect(giveUps).toEqual([]); |
| 55 | + expect(calls).toEqual( |
| 56 | + Array.from({ length: 3 }, () => ({ |
| 57 | + url, |
| 58 | + method: "QUERY", |
| 59 | + body, |
| 60 | + contentType: "application/json", |
| 61 | + csrf: null, |
| 62 | + })), |
| 63 | + ); |
| 64 | +}); |