|
| 1 | +import type { Middleware, MiddlewareContext } from '@pyreon/server' |
| 2 | +import type { ApiHandler, ApiRouteEntry } from './api-routes' |
| 3 | +import { createApiMiddleware } from './api-routes' |
| 4 | + |
| 5 | +// ─── Test helpers for Zero applications ───────────────────────────────────── |
| 6 | + |
| 7 | +/** |
| 8 | + * Create a mock MiddlewareContext for testing middleware. |
| 9 | + * |
| 10 | + * @example |
| 11 | + * import { createTestContext } from "@pyreon/zero/testing" |
| 12 | + * |
| 13 | + * const ctx = createTestContext("/api/posts", { method: "POST", body: { title: "Hello" } }) |
| 14 | + * const result = await myMiddleware(ctx) |
| 15 | + */ |
| 16 | +export function createTestContext( |
| 17 | + path: string, |
| 18 | + options: { |
| 19 | + method?: string |
| 20 | + headers?: Record<string, string> |
| 21 | + body?: unknown |
| 22 | + } = {}, |
| 23 | +): MiddlewareContext { |
| 24 | + const { method = 'GET', headers = {}, body } = options |
| 25 | + const url = new URL(`http://localhost${path}`) |
| 26 | + |
| 27 | + const requestHeaders: Record<string, string> = { ...headers } |
| 28 | + let requestBody: string | undefined |
| 29 | + |
| 30 | + if (body !== undefined) { |
| 31 | + requestHeaders['Content-Type'] = 'application/json' |
| 32 | + requestBody = JSON.stringify(body) |
| 33 | + } |
| 34 | + |
| 35 | + const req = new Request(url.toString(), { |
| 36 | + method, |
| 37 | + headers: requestHeaders, |
| 38 | + body: requestBody, |
| 39 | + }) |
| 40 | + |
| 41 | + return { |
| 42 | + req, |
| 43 | + url, |
| 44 | + path, |
| 45 | + headers: new Headers(), |
| 46 | + locals: {}, |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * Test a middleware by running it with a mock context and returning |
| 52 | + * the result along with the response headers it set. |
| 53 | + * |
| 54 | + * @example |
| 55 | + * import { testMiddleware } from "@pyreon/zero/testing" |
| 56 | + * |
| 57 | + * const { response, headers } = await testMiddleware( |
| 58 | + * corsMiddleware({ origin: "*" }), |
| 59 | + * "/api/posts" |
| 60 | + * ) |
| 61 | + * expect(headers.get("Access-Control-Allow-Origin")).toBe("*") |
| 62 | + */ |
| 63 | +export async function testMiddleware( |
| 64 | + middleware: Middleware, |
| 65 | + path: string, |
| 66 | + options: { |
| 67 | + method?: string |
| 68 | + headers?: Record<string, string> |
| 69 | + body?: unknown |
| 70 | + } = {}, |
| 71 | +): Promise<{ response: Response | undefined; headers: Headers }> { |
| 72 | + const ctx = createTestContext(path, options) |
| 73 | + const response = (await middleware(ctx)) as Response | undefined |
| 74 | + return { response, headers: ctx.headers } |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * Create a test server for API routes. Returns a function that |
| 79 | + * accepts Request objects and dispatches to the correct handler. |
| 80 | + * |
| 81 | + * @example |
| 82 | + * import { createTestApiServer } from "@pyreon/zero/testing" |
| 83 | + * |
| 84 | + * const server = createTestApiServer([ |
| 85 | + * { pattern: "/api/posts", module: postsApi }, |
| 86 | + * { pattern: "/api/posts/:id", module: postByIdApi }, |
| 87 | + * ]) |
| 88 | + * |
| 89 | + * const response = await server.request("/api/posts") |
| 90 | + * expect(response.status).toBe(200) |
| 91 | + * |
| 92 | + * const data = await server.request("/api/posts", { method: "POST", body: { title: "Hi" } }) |
| 93 | + * expect(data.status).toBe(201) |
| 94 | + */ |
| 95 | +export function createTestApiServer(routes: ApiRouteEntry[]) { |
| 96 | + const middleware = createApiMiddleware(routes) |
| 97 | + |
| 98 | + return { |
| 99 | + async request( |
| 100 | + path: string, |
| 101 | + options: { |
| 102 | + method?: string |
| 103 | + headers?: Record<string, string> |
| 104 | + body?: unknown |
| 105 | + } = {}, |
| 106 | + ): Promise<Response> { |
| 107 | + const ctx = createTestContext(path, options) |
| 108 | + const result = await middleware(ctx) |
| 109 | + if (!result) { |
| 110 | + return new Response('Not Found', { status: 404 }) |
| 111 | + } |
| 112 | + return result |
| 113 | + }, |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +/** |
| 118 | + * Create a mock API handler for testing. |
| 119 | + * Records all calls and returns a configurable response. |
| 120 | + * |
| 121 | + * @example |
| 122 | + * import { createMockHandler } from "@pyreon/zero/testing" |
| 123 | + * |
| 124 | + * const handler = createMockHandler({ status: 200, body: { ok: true } }) |
| 125 | + * // ... use handler in your API route module |
| 126 | + * expect(handler.calls).toHaveLength(1) |
| 127 | + * expect(handler.calls[0].params).toEqual({ id: "123" }) |
| 128 | + */ |
| 129 | +export function createMockHandler( |
| 130 | + responseConfig: { |
| 131 | + status?: number |
| 132 | + body?: unknown |
| 133 | + headers?: Record<string, string> |
| 134 | + } = {}, |
| 135 | +): ApiHandler & { |
| 136 | + calls: Array<{ path: string; params: Record<string, string> }> |
| 137 | +} { |
| 138 | + const { status = 200, body = null, headers = {} } = responseConfig |
| 139 | + const calls: Array<{ path: string; params: Record<string, string> }> = [] |
| 140 | + |
| 141 | + const handler: ApiHandler = (ctx) => { |
| 142 | + calls.push({ path: ctx.path, params: ctx.params }) |
| 143 | + return new Response(JSON.stringify(body), { |
| 144 | + status, |
| 145 | + headers: { 'Content-Type': 'application/json', ...headers }, |
| 146 | + }) |
| 147 | + } |
| 148 | + |
| 149 | + return Object.assign(handler, { calls }) |
| 150 | +} |
0 commit comments