Преглед на файлове

📝 docs(test): update integration testing documentation with testClient examples

- add testClient integration testing approach using hono/testing
- provide detailed TypeScript examples for mocking API client with testClient
- include code samples for replacing mock with testClient in user routes testing
- add test mode recommendation for better type safety and maintainability
yourname преди 2 месеца
родител
ревизия
412fab8a0b
променени са 1 файла, в които са добавени 58 реда и са изтрити 0 реда
  1. 58 0
      docs/stories/001.004.story.md

+ 58 - 0
docs/stories/001.004.story.md

@@ -53,6 +53,7 @@ Ready for Development
 
 ### 测试策略
 **集成测试重点** (`src/client/admin/__integration_tests__/`):
+- 使用 `hono/testing` 的 `testClient` 进行类型安全的API集成测试
 - 组件与真实API集成测试 [API端点: /api/users/*, /api/auth/login]
 - 用户界面行为和数据流测试
 - 表单验证和错误处理测试
@@ -70,10 +71,67 @@ Ready for Development
 - **性能**: 测试执行时间合理(集成测试<5分钟,E2E测试<10分钟)
 - **测试数据**: 使用测试数据库事务回滚确保数据隔离 [参考: docs/integration-testing-best-practices.md]
 - **环境要求**: 需要配置测试数据库连接和认证token
+
+### testClient 集成测试示例
+```typescript
+// 在集成测试中使用 testClient 替代 mock
+import { testClient } from 'hono/testing';
+import { userRoutes } from '@/server/api';
+
+// 由于 hc() 和 testClient() 返回结构相似,可以直接替换
+vi.mock('@/client/api', () => {
+  const testApiClient = testClient(userRoutes).api.v1;
+
+  return {
+    userClient: testApiClient.users  // 直接使用 testClient 的 users 接口
+  };
+});
+
+// 或者更灵活的方式:在测试中动态控制 mock 行为
+vi.mock('@/client/api', async (importOriginal) => {
+  const original = await importOriginal();
+  const testApiClient = testClient(userRoutes).api.v1;
+
+  return {
+    ...original,
+    userClient: {
+      // 使用 testClient 作为基础,但可以覆盖特定方法
+      $get: vi.fn().mockImplementation((params) =>
+        testApiClient.users.$get(params)
+      ),
+      $post: vi.fn().mockImplementation((params) =>
+        testApiClient.users.$post(params)
+      ),
+      ':id': {
+        $put: vi.fn().mockImplementation((params) =>
+          testApiClient.users[':id'].$put(params)
+        ),
+        $delete: vi.fn().mockImplementation((params) =>
+          testApiClient.users[':id'].$delete(params)
+        )
+      }
+    }
+  };
+});
+
+// 测试中使用真实的类型安全调用
+describe('UsersPage 集成测试', () => {
+  it('应该正确处理用户列表请求', async () => {
+    // 组件会通过 userClient.$get() 调用,现在使用 testClient 的实现
+    render(<UsersPage />);
+
+    // 验证组件正确渲染了 testClient 返回的数据
+    await waitFor(() => {
+      expect(screen.getByText('admin')).toBeInTheDocument();
+    });
+  });
+});
+```
 - **测试位置**:
   - 集成测试: `src/client/admin/__integration_tests__/*.test.tsx` (使用 `.test.tsx` 后缀以匹配现有配置)
   - E2E测试: `tests/e2e/specs/admin/*.spec.ts`
   - 现有单元测试: `src/client/admin/**/__tests__/*.test.tsx` (保持不变)
+- **测试模式**: 集成测试推荐使用 `hono/testing` 的 `testClient` 以获得更好的类型安全和维护性
 
 ### 集成点
 - **现有Vitest配置**: vitest.config.components.ts (组件测试), vitest.config.ts (API测试)