| 19 | }; |
| 20 | |
| 21 | export const testServerRoute = ( |
| 22 | server: SetupServer, |
| 23 | path: string, |
| 24 | json: object | boolean | string | number, |
| 25 | method: 'get' | 'post' | 'put' | 'delete' = 'get', |
| 26 | status: number = 200, |
| 27 | searchParams?: Record<string, string>, |
| 28 | ) => { |
| 29 | const requests: unknown[] = []; |
| 30 | server.use( |
| 31 | http[method](path, async ({ request }) => { |
| 32 | if (searchParams) { |
| 33 | const url = new URL(request.url); |
| 34 | const matches = Object.entries(searchParams).every( |
| 35 | ([key, value]) => url.searchParams.get(key) === value, |
| 36 | ); |
| 37 | // Fall through to other handlers for this path when the |
| 38 | // search params don't match. |
| 39 | if (!matches) return undefined; |
| 40 | } |
| 41 | if (method === 'post' || method === 'put') { |
| 42 | const body = await request.json().catch(() => undefined); |
| 43 | if (body !== undefined) { |
| 44 | requests.push(body); |
| 45 | } |
| 46 | } |
| 47 | return HttpResponse.json(json, { status }); |
| 48 | }), |
| 49 | ); |
| 50 | return { requests }; |
| 51 | }; |