Files
cms-client/tests/e2e/helpers/mock.ts
2026-04-18 12:14:30 +08:00

48 lines
1.4 KiB
TypeScript

export type RecordedRequest = {
method: string;
path: string;
query: Record<string, string>;
body: unknown;
headers: Record<string, string>;
};
const MOCK = 'http://localhost:4010';
const post = (path: string, body: unknown) =>
fetch(`${MOCK}${path}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body)
});
export const mock = {
/**
* Register a response for a given (method, pathPattern). Last writer wins
* for the same key — a later override replaces an earlier one mid-test.
*/
override: (
method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE',
pathPattern: string,
response: { status: number; body?: unknown; headers?: Record<string, string> }
) => post('/__test/override', { method, pathPattern, response }),
/**
* Return recorded requests matching the filter, newest first.
* For "did the UI re-fetch?" assertions, check `.length`, not just `[0]`.
*/
requests: (filter: { method?: string; path?: string } = {}): Promise<RecordedRequest[]> => {
const qs = new URLSearchParams(
Object.entries(filter).filter(([, v]) => v !== undefined) as [string, string][]
);
return fetch(`${MOCK}/__test/requests?${qs}`).then(
(r) => r.json() as Promise<RecordedRequest[]>
);
},
/**
* Clear override table + request log. Wired to `beforeEach` once in
* `fixtures.ts`; tests don't call this directly.
*/
clear: () => fetch(`${MOCK}/__test/override`, { method: 'DELETE' })
};