| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- 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<string, string>) =>
- makeRequest('GET', path, undefined, headers),
- post: (path: string, body?: any, headers?: Record<string, string>) =>
- makeRequest('POST', path, body, headers),
- put: (path: string, body?: any, headers?: Record<string, string>) =>
- makeRequest('PUT', path, body, headers),
- delete: (path: string, headers?: Record<string, string>) =>
- makeRequest('DELETE', path, undefined, headers),
- patch: (path: string, body?: any, headers?: Record<string, string>) =>
- makeRequest('PATCH', path, body, headers)
- };
- async function makeRequest(
- method: string,
- path: string,
- body?: any,
- customHeaders?: Record<string, string>
- ) {
- const url = new URL(path, 'http://localhost:3000');
- const headers: Record<string, string> = {
- '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<string, string> = {};
- 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}`);
- }
- }
- }
|