hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits
| 1 | import { vi } from "vitest"; |
| 2 | |
| 3 | /** |
| 4 | * Shared fetch-mocking helpers for API tests. |
| 5 | * |
| 6 | * Every helper calls `vi.stubGlobal("fetch", ...)` so a single |
| 7 | * `afterEach(() => vi.restoreAllMocks())` in each test file is enough. |
| 8 | */ |
| 9 | |
| 10 | type FetchFn = typeof globalThis.fetch; |
| 11 | |
| 12 | /** Return the `[url, init]` pair from the most recent `fetch` call. */ |
| 13 | export function lastFetchCall(): [string, RequestInit | undefined] { |
| 14 | const fn = globalThis.fetch as ReturnType<typeof vi.fn>; |
| 15 | const calls = fn.mock.calls as [string, RequestInit | undefined][]; |
| 16 | return calls[calls.length - 1]; |
| 17 | } |
| 18 | |
| 19 | /** Stub fetch to return a successful JSON response. */ |
| 20 | export function mockFetchSuccess(data: unknown, status = 200): void { |
| 21 | const fn: FetchFn = async () => |
| 22 | new Response(JSON.stringify(data), { |
| 23 | status, |
| 24 | headers: { "Content-Type": "application/json" }, |
| 25 | }); |
| 26 | vi.stubGlobal("fetch", vi.fn(fn)); |
| 27 | } |
| 28 | |
| 29 | /** Stub fetch to return a 204 No Content response. */ |
| 30 | export function mockFetch204(): void { |
| 31 | const fn: FetchFn = async () => new Response(null, { status: 204 }); |
| 32 | vi.stubGlobal("fetch", vi.fn(fn)); |
| 33 | } |
| 34 | |
| 35 | /** Stub fetch to return an error JSON response. */ |
| 36 | export function mockFetchError(status: number, body?: Record<string, unknown>, headers?: Record<string, string>): void { |
| 37 | const fn: FetchFn = async () => |
| 38 | new Response(body ? JSON.stringify(body) : null, { |
| 39 | status, |
| 40 | statusText: "Error", |
| 41 | headers: { |
| 42 | "Content-Type": "application/json", |
| 43 | ...headers, |
| 44 | }, |
| 45 | }); |
| 46 | vi.stubGlobal("fetch", vi.fn(fn)); |
| 47 | } |
| 48 | |
| 49 | /** Stub fetch to return a Blob response. */ |
| 50 | export function mockFetchBlob(blob: Blob): void { |
| 51 | const fn: FetchFn = async () => |
| 52 | new Response(blob, { |
| 53 | status: 200, |
| 54 | headers: { "Content-Type": blob.type || "application/octet-stream" }, |
| 55 | }); |
| 56 | vi.stubGlobal("fetch", vi.fn(fn)); |
| 57 | } |