test-utils.ts 2.1 KB

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