import { OpenAPIHono } from '@hono/zod-openapi'; import { Hono } from 'hono'; import { DataSource } from 'typeorm'; export interface TestServerOptions { setupAuth?: boolean; setupDatabase?: boolean; setupMiddlewares?: boolean; } /** * 创建测试服务器实例 */ export function createTestServer( app: OpenAPIHono | Hono, options: TestServerOptions = {} ) { const server = app; // 设置默认选项 const { setupAuth = true } = options; return { get: (path: string, headers?: Record) => makeRequest('GET', path, undefined, headers), post: (path: string, body?: any, headers?: Record) => makeRequest('POST', path, body, headers), put: (path: string, body?: any, headers?: Record) => makeRequest('PUT', path, body, headers), delete: (path: string, headers?: Record) => makeRequest('DELETE', path, undefined, headers), patch: (path: string, body?: any, headers?: Record) => makeRequest('PATCH', path, body, headers) }; async function makeRequest( method: string, path: string, body?: any, customHeaders?: Record ) { const url = new URL(path, 'http://localhost:3000'); const headers: Record = { 'Content-Type': 'application/json', ...(setupAuth && { 'Authorization': 'Bearer test-token-123' }), ...customHeaders }; const request = new Request(url.toString(), { method, headers, body: body ? JSON.stringify(body) : undefined, }); try { const response = await server.fetch(request); const responseHeaders: Record = {}; response.headers.forEach((value: string, key: string) => { responseHeaders[key] = value; }); let responseData: any; const contentType = response.headers.get('content-type'); if (contentType?.includes('application/json')) { responseData = await response.json(); } else { responseData = await response.text(); } return { status: response.status, headers: responseHeaders, data: responseData, json: async () => responseData, text: async () => responseData }; } catch (error) { throw new Error(`Request failed: ${error}`); } } }