test-utils.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. 'Authorization': 'Bearer mock-token',
  22. },
  23. body: body ? JSON.stringify(body) : undefined,
  24. });
  25. try {
  26. const response = await server.fetch(request);
  27. return {
  28. status: response.status,
  29. headers: response.headers,
  30. json: async () => response.json(),
  31. text: async () => response.text()
  32. };
  33. } catch (error) {
  34. throw new Error(`Request failed: ${error}`);
  35. }
  36. }
  37. }
  38. /**
  39. * 创建模拟的认证上下文
  40. */
  41. export function createMockAuthContext() {
  42. return {
  43. req: {
  44. header: (name: string) => {
  45. if (name === 'authorization') return 'Bearer mock-token';
  46. return null;
  47. }
  48. },
  49. set: vi.fn(),
  50. json: vi.fn().mockImplementation((data, status = 200) => ({
  51. status,
  52. body: data
  53. })),
  54. env: {},
  55. var: {}
  56. };
  57. }
  58. /**
  59. * 创建模拟的用户实体
  60. */
  61. export function createMockUser(overrides: Partial<any> = {}) {
  62. return {
  63. id: 1,
  64. username: 'testuser',
  65. email: 'test@example.com',
  66. password: 'hashed_password',
  67. phone: '13800138000',
  68. nickname: 'Test User',
  69. status: 1,
  70. createdAt: new Date(),
  71. updatedAt: new Date(),
  72. roles: [],
  73. ...overrides
  74. };
  75. }
  76. /**
  77. * 等待指定时间
  78. */
  79. export function wait(ms: number) {
  80. return new Promise(resolve => setTimeout(resolve, ms));
  81. }