109 lines
2.4 KiB
TypeScript
Executable file
109 lines
2.4 KiB
TypeScript
Executable file
/**
|
|
* Fetch Mock Utilities
|
|
*
|
|
* Helper functions for mocking fetch API in tests.
|
|
*/
|
|
|
|
import { vi } from 'vitest'
|
|
|
|
export interface FetchMockResponse<T = unknown> {
|
|
ok: boolean
|
|
status: number
|
|
statusText: string
|
|
data?: T
|
|
error?: string
|
|
}
|
|
|
|
/**
|
|
* Create a mock fetch function
|
|
*/
|
|
export function createFetchMock(): ReturnType<typeof vi.fn> {
|
|
return vi.fn()
|
|
}
|
|
|
|
/**
|
|
* Mock a successful fetch response
|
|
*/
|
|
export function mockFetchSuccess<T>(data: T, status = 200): Response {
|
|
return {
|
|
ok: true,
|
|
status,
|
|
statusText: 'OK',
|
|
json: () => Promise.resolve(data),
|
|
text: () => Promise.resolve(JSON.stringify(data)),
|
|
headers: new Headers(),
|
|
redirected: false,
|
|
type: 'basic',
|
|
url: '',
|
|
clone: () => mockFetchSuccess(data, status),
|
|
body: null,
|
|
bodyUsed: false,
|
|
arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)),
|
|
blob: () => Promise.resolve(new Blob()),
|
|
formData: () => Promise.resolve(new FormData()),
|
|
} as Response
|
|
}
|
|
|
|
/**
|
|
* Mock an error fetch response
|
|
*/
|
|
export function mockFetchError(message: string, status = 400): Response {
|
|
return {
|
|
ok: false,
|
|
status,
|
|
statusText: 'Bad Request',
|
|
json: () => Promise.resolve({ message }),
|
|
text: () => Promise.resolve(JSON.stringify({ message })),
|
|
headers: new Headers(),
|
|
redirected: false,
|
|
type: 'basic',
|
|
url: '',
|
|
clone: () => mockFetchError(message, status),
|
|
body: null,
|
|
bodyUsed: false,
|
|
arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)),
|
|
blob: () => Promise.resolve(new Blob()),
|
|
formData: () => Promise.resolve(new FormData()),
|
|
} as Response
|
|
}
|
|
|
|
/**
|
|
* Mock a sequence of fetch responses
|
|
*/
|
|
export function mockFetchSequence(
|
|
responses: Array<{ url: string | RegExp; response: Response }>
|
|
): typeof global.fetch {
|
|
const fetchMock = vi.fn().mockImplementation((url: string) => {
|
|
const match = responses.find((r) => {
|
|
if (typeof r.url === 'string') {
|
|
return url.includes(r.url)
|
|
}
|
|
return r.url.test(url)
|
|
})
|
|
|
|
if (match) {
|
|
return Promise.resolve(match.response)
|
|
}
|
|
|
|
return Promise.resolve(mockFetchError('Not found', 404))
|
|
})
|
|
|
|
global.fetch = fetchMock
|
|
return fetchMock
|
|
}
|
|
|
|
/**
|
|
* Setup global fetch mock
|
|
*/
|
|
export function setupFetchMock(): ReturnType<typeof vi.fn> {
|
|
const fetchMock = createFetchMock()
|
|
global.fetch = fetchMock
|
|
return fetchMock
|
|
}
|
|
|
|
/**
|
|
* Reset global fetch mock
|
|
*/
|
|
export function resetFetchMock(): void {
|
|
vi.mocked(global.fetch).mockReset()
|
|
}
|