102 lines
2.6 KiB
TypeScript
102 lines
2.6 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
/**
|
|
* Manual mock for `@/src/lib/fetch-json`.
|
|
*
|
|
* The catalogue pages load products/slots/stores/availability from versioned
|
|
* CDN JSON documents. This mock keys responses by URL (exact string, RegExp or
|
|
* predicate) so tests can seed and override those documents per case.
|
|
*/
|
|
|
|
type Matcher = string | RegExp | ((url: string) => boolean)
|
|
|
|
interface JsonEntry {
|
|
matcher: Matcher
|
|
data?: any
|
|
error?: unknown
|
|
pending?: boolean
|
|
once?: boolean
|
|
}
|
|
|
|
const entries: JsonEntry[] = []
|
|
const calls: string[] = []
|
|
|
|
export const JSON_FETCH_TIMEOUT_MS = 90_000
|
|
|
|
export function isAbortError(error: unknown): boolean {
|
|
if (!error || typeof error !== 'object') return false
|
|
const candidate = error as { name?: string; code?: string }
|
|
return (
|
|
candidate.name === 'CanceledError' ||
|
|
candidate.name === 'AbortError' ||
|
|
candidate.code === 'ERR_CANCELED'
|
|
)
|
|
}
|
|
|
|
function matches(matcher: Matcher, url: string): boolean {
|
|
if (typeof matcher === 'string') return matcher === url
|
|
if (matcher instanceof RegExp) return matcher.test(url)
|
|
return matcher(url)
|
|
}
|
|
|
|
function findEntry(url: string): JsonEntry | undefined {
|
|
for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
const entry = entries[i]
|
|
if (matches(entry.matcher, url)) {
|
|
if (entry.once) entries.splice(i, 1)
|
|
return entry
|
|
}
|
|
}
|
|
return undefined
|
|
}
|
|
|
|
export function setJsonResponse(matcher: Matcher, data: any, options: { once?: boolean } = {}) {
|
|
entries.push({ matcher, data, once: options.once })
|
|
}
|
|
|
|
export function setJsonError(matcher: Matcher, error?: unknown, options: { once?: boolean } = {}) {
|
|
entries.push({
|
|
matcher,
|
|
error: error ?? new Error(`JSON fetch failed for ${String(matcher)}`),
|
|
once: options.once,
|
|
})
|
|
}
|
|
|
|
export function setJsonPending(matcher: Matcher) {
|
|
entries.push({ matcher, pending: true })
|
|
}
|
|
|
|
export function resetJsonMocks() {
|
|
entries.length = 0
|
|
calls.length = 0
|
|
}
|
|
|
|
export function jsonCalls(): string[] {
|
|
return [...calls]
|
|
}
|
|
|
|
export function jsonCallsFor(matcher: Matcher): string[] {
|
|
return calls.filter((url) => matches(matcher, url))
|
|
}
|
|
|
|
export function resetJsonCalls() {
|
|
calls.length = 0
|
|
}
|
|
|
|
export async function fetchJson<T>(url: string, _timeoutMs?: number): Promise<T> {
|
|
calls.push(url)
|
|
const entry = findEntry(url)
|
|
if (!entry) {
|
|
throw new Error(`[fetch-json mock] no response registered for ${url}`)
|
|
}
|
|
if (entry.pending) {
|
|
return new Promise<T>(() => {
|
|
/* never settles */
|
|
})
|
|
}
|
|
if (entry.error !== undefined) {
|
|
throw entry.error
|
|
}
|
|
return entry.data as T
|
|
}
|
|
|
|
export default { fetchJson }
|