Files
ToBePlayed-Frontend/src/test/fetchRoutes.js
T

28 lines
1.2 KiB
JavaScript

import {onTestFinished, vi} from 'vitest';
export const json = (status, body) => ({ok: status >= 200 && status < 300, status, json: async () => body});
/**
* A fetch mock that answers by method and path, e.g. `'GET /api/users/me'`. The path starts at `/api/` (the base URL
* is not set in tests) and leaves out the query. A value is an answer or `(url, init) => answer`. Any other request
* rejects, and the test fails at its end even when the page catches the error.
* Sets `globalThis.fetch` and returns the mock.
*/
export function fetchRoutes(routes) {
const unknown = [];
const mock = vi.fn(async (url, init) => {
const key = `${init?.method ?? 'GET'} ${new URL(url, 'http://x').pathname.replace(/^.*?(?=\/api\/)/, '')}`;
if (!(key in routes)) {
unknown.push(key);
throw new Error(`no route ${key}`);
}
const answer = routes[key];
return typeof answer === 'function' ? answer(url, init) : answer;
});
globalThis.fetch = mock;
onTestFinished(() => {
if (unknown.length) throw new Error(`requests without a route: ${[...new Set(unknown)].join(', ')}`);
});
return mock;
}