test: add API mock, fixtures, and DOM helpers for tests

This commit is contained in:
2026-04-21 11:23:21 +02:00
committed by djalim
parent 612c41c099
commit 332286c085
3 changed files with 218 additions and 0 deletions
+56
View File
@@ -0,0 +1,56 @@
// Mock de fetch() pour les tests
// deno-lint-ignore no-explicit-any
let _originalFetch: ((input: any, init?: any) => Promise<Response>) | null =
null;
/**
* Remplace globalThis.fetch par un mock qui retourne des réponses
* pré-configurées selon l'URL.
*
* @param routes - Map URL pattern → données de réponse (sera sérialisé en JSON)
*/
export function mockFetch(
routes: Record<string, unknown>,
): void {
_originalFetch = globalThis.fetch;
globalThis.fetch = (
input: string | URL | Request,
_init?: RequestInit,
): Promise<Response> => {
const url = typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input.url;
for (const [pattern, data] of Object.entries(routes)) {
if (url.includes(pattern)) {
return Promise.resolve(
new Response(JSON.stringify(data), {
status: 200,
headers: { "Content-Type": "application/json" },
}),
);
}
}
return Promise.resolve(
new Response(JSON.stringify({ error: "Not Found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
}),
);
};
}
/**
* Restaure le fetch original.
*/
export function restoreFetch(): void {
if (_originalFetch) {
globalThis.fetch = _originalFetch;
_originalFetch = null;
}
}