2
0
Эх сурвалжийг харах

✅ test(auth): 优化手机号解密API测试的Redis依赖模拟方式

- 将全局mock改为更精确的spyOn方式模拟redisUtil.getSessionKey
- 添加afterEach钩子清理mock,避免测试间相互影响
- 使用mockResolvedValue直接修改返回值,简化测试代码
- 提高测试隔离性和可维护性
yourname 3 долоо хоног өмнө
parent
commit
45a0e8de3c

+ 14 - 19
packages/auth-module/tests/integration/phone-decrypt.integration.test.ts

@@ -3,6 +3,7 @@ import { testClient } from 'hono/testing';
 import { authRoutes } from '../../src/routes';
 import { IntegrationTestDatabase, setupIntegrationDatabaseHooksWithEntities } from '@d8d/shared-test-util';
 import { UserEntity } from '@d8d/user-module';
+import { redisUtil } from '@d8d/shared-utils';
 import { File } from '@d8d/file-module';
 
 // Mock MiniAuthService 的 decryptPhoneNumber 方法
@@ -26,18 +27,6 @@ vi.mock('../../src/services/mini-auth.service', () => ({
   }))
 }));
 
-// Mock Redis 依赖
-vi.mock('@d8d/shared-utils', async (importOriginal) => {
-  const actual = await importOriginal() as any;
-  return {
-    ...actual,
-    redisUtil: {
-      getSessionKey: vi.fn().mockResolvedValue('mock-session-key')
-    },
-    ErrorSchema: actual.ErrorSchema // 确保ErrorSchema被正确导出
-  };
-});
-
 // 设置集成测试钩子
 setupIntegrationDatabaseHooksWithEntities([UserEntity, File])
 
@@ -45,6 +34,7 @@ describe('手机号解密API集成测试', () => {
   let client: ReturnType<typeof testClient<typeof authRoutes>>;
   let testToken: string;
   let testUser: UserEntity;
+  let getSessionKeySpy: any;
 
   beforeEach(async () => {
     // 创建测试客户端
@@ -67,6 +57,16 @@ describe('手机号解密API集成测试', () => {
     // 生成测试用户的token
     // 这里简化处理,实际项目中应该使用正确的JWT生成方法
     testToken = 'test_jwt_token';
+
+    // 使用 spyOn 来 mock getSessionKey 方法
+    getSessionKeySpy = vi.spyOn(redisUtil, 'getSessionKey').mockResolvedValue('mock-session-key');
+  });
+
+  afterEach(() => {
+    // 清理 spy
+    if (getSessionKeySpy) {
+      getSessionKeySpy.mockRestore();
+    }
   });
 
   describe('POST /auth/phone-decrypt', () => {
@@ -212,13 +212,8 @@ describe('手机号解密API集成测试', () => {
         iv: 'encryption_iv'
       };
 
-      // Mock Redis 返回空的 sessionKey
-      vi.mock('@d8d/shared-utils', () => ({
-        ...vi.importActual('@d8d/shared-utils'),
-        redisUtil: {
-          getSessionKey: vi.fn().mockResolvedValue(null)
-        }
-      }));
+      // 模拟 sessionKey 过期的情况
+      getSessionKeySpy.mockResolvedValue(null);
 
       const response = await client['phone-decrypt'].$post({
         json: requestData