(opts: MockServerOptions)
| 11 | } |
| 12 | |
| 13 | export function createMockServer(opts: MockServerOptions): MockServer { |
| 14 | const server = Bun.serve({ |
| 15 | port: 0, // Random available port |
| 16 | fetch(req) { |
| 17 | const url = new URL(req.url); |
| 18 | const path = url.pathname; |
| 19 | |
| 20 | // Try exact match first |
| 21 | const handler = opts.routes[path] || opts.routes[`${req.method} ${path}`]; |
| 22 | if (handler) { |
| 23 | return handler(req); |
| 24 | } |
| 25 | |
| 26 | // Try prefix match |
| 27 | for (const [pattern, handler] of Object.entries(opts.routes)) { |
| 28 | if (path.startsWith(pattern)) { |
| 29 | return handler(req); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | return new Response(JSON.stringify({ error: 'Not found' }), { |
| 34 | status: 404, |
| 35 | headers: { 'Content-Type': 'application/json' }, |
| 36 | }); |
| 37 | }, |
| 38 | }); |
| 39 | |
| 40 | return { |
| 41 | url: `http://localhost:${server.port}`, |
| 42 | port: server.port!, |
| 43 | close() { |
| 44 | server.stop(); |
| 45 | }, |
| 46 | }; |
| 47 | } |
| 48 | |
| 49 | export function jsonResponse(data: unknown, status = 200): Response { |
| 50 | return new Response(JSON.stringify(data), { |
no outgoing calls
no test coverage detected