2
0

test-utils.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { OpenAPIHono } from '@hono/zod-openapi';
  2. import { Hono } from 'hono';
  3. /**
  4. * 创建测试服务器实例
  5. */
  6. export function createTestServer(app: OpenAPIHono | Hono) {
  7. const server = app as any;
  8. return {
  9. get: (path: string) => makeRequest('GET', path),
  10. post: (path: string, body?: any) => makeRequest('POST', path, body),
  11. put: (path: string, body?: any) => makeRequest('PUT', path, body),
  12. delete: (path: string) => makeRequest('DELETE', path),
  13. patch: (path: string, body?: any) => makeRequest('PATCH', path, body)
  14. };
  15. async function makeRequest(method: string, path: string, body?: any) {
  16. const url = new URL(path, 'http://localhost:3000');
  17. const request = new Request(url.toString(), {
  18. method,
  19. headers: {
  20. 'Content-Type': 'application/json',
  21. },
  22. body: body ? JSON.stringify(body) : undefined,
  23. });
  24. try {
  25. const response = await server.fetch(request);
  26. return {
  27. status: response.status,
  28. headers: response.headers,
  29. json: async () => response.json(),
  30. text: async () => response.text()
  31. };
  32. } catch (error) {
  33. throw new Error(`Request failed: ${error}`);
  34. }
  35. }
  36. }
  37. /**
  38. * 创建模拟的认证上下文
  39. */
  40. export function createMockAuthContext() {
  41. return {
  42. req: {
  43. header: (name: string) => {
  44. if (name === 'authorization') return 'Bearer mock-token';
  45. return null;
  46. }
  47. },
  48. set: jest.fn(),
  49. json: jest.fn().mockImplementation((data, status = 200) => ({
  50. status,
  51. body: data
  52. })),
  53. env: {},
  54. var: {}
  55. };
  56. }
  57. /**
  58. * 创建模拟的用户实体
  59. */
  60. export function createMockUser(overrides: Partial<any> = {}) {
  61. return {
  62. id: 1,
  63. username: 'testuser',
  64. email: 'test@example.com',
  65. password: 'hashed_password',
  66. phone: '13800138000',
  67. nickname: 'Test User',
  68. status: 1,
  69. createdAt: new Date(),
  70. updatedAt: new Date(),
  71. roles: [],
  72. ...overrides
  73. };
  74. }
  75. /**
  76. * 等待指定时间
  77. */
  78. export function wait(ms: number) {
  79. return new Promise(resolve => setTimeout(resolve, ms));
  80. }