Public Access
test: data router, one render helper, fetchRoutes in every test
This commit is contained in:
1 parent
d0ea9e900d
commit
2a22789435
37 files changed
+454
-425
No files matched your search
+10
-3
@@ -1,20 +1,27 @@
|
||||
import {vi} from 'vitest';
|
||||
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
|
||||
* throws, so a test cannot pass on a request it did not expect.
|
||||
* 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)) throw new Error(`no route ${key}`);
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user