Open History to see the last commit
1import { vi } from 'vitest'
2
3export function mockFetch(payload: unknown, status = 200, statusText = '') {
4 return vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => {
5 return new Response(JSON.stringify(payload), {
6 status,
7 statusText,
8 headers: { 'Content-Type': 'application/json' },
9 })
10 })
11}
12
13export function firstFetchCall(fetchMock: ReturnType<typeof mockFetch>): {
14 url: string
15 init: RequestInit
16} {
17 const call = fetchMock.mock.calls[0]
18 const input = call?.[0]
19 const init = call?.[1]
20 if (input === undefined || init === undefined) {
21 throw new Error('expected fetch to be called with a URL and RequestInit')
22 }
23 return {
24 url: typeof input === 'string' ? input : String(input),
25 init,
26 }
27}
28
29export function firstFetchBody(
30 fetchMock: ReturnType<typeof mockFetch>,
31): Record<string, unknown> {
32 return JSON.parse(String(firstFetchCall(fetchMock).init.body)) as Record<
33 string,
34 unknown
35 >
36}
37
38export function firstFetchHeaders(
39 fetchMock: ReturnType<typeof mockFetch>,
40): Record<string, string> {
41 const headers = firstFetchCall(fetchMock).init.headers
42 if (!headers || Array.isArray(headers) || headers instanceof Headers) {
43 throw new Error('expected fetch headers as a record')
44 }
45 return headers
46}