Jest测试Nest.js集成Sequelize时authService.find返回undefined如何解决
问题排查与解决步骤
- 首先删除无效的全局mock语句:你代码中写的
jest.mock('./../../modules/auth/auth.service')会将整个AuthService的所有方法默认mock为返回undefined,即使你在测试模块中声明了AuthService的provider,调用的也是被全局mock后的空方法,自然拿不到返回值。 - 如果你选择使用真实的AuthService仅mock其依赖的Auth模型,按以下步骤修正:
- 确认AuthService的
find方法内部正确调用了Auth模型的findOne方法,且参数转换逻辑正确,比如是否将入参的id正确传入findOne的where条件中 - 将Auth模型的mock方法改为返回Promise,更贴合Sequelize的真实行为:
findOne: jest.fn(() => Promise.resolve(testAuth)) - 检查testAuth的属性和业务代码读取的属性匹配:你当前初始化testAuth时只传入了
id_user: '1',但业务代码中读取的是user.id,需要保持属性名一致,要么给testAuth添加id: '1',要么将业务代码的读取逻辑改为user.id_user
- 确认AuthService的
- 更推荐的单元测试方案:如果你是测试AuthGuardService的逻辑,不需要验证AuthService的内部实现,直接mock AuthService的
find方法即可,不需要引入Sequelize、Auth模型相关的依赖,代码更简洁:describe('AuthGuardService', () => { let service: AuthGuardService; let authService: AuthService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ AuthGuardService, { provide: AuthService, useValue: { find: jest.fn().mockResolvedValue({ id: '1' }) // 直接mock你需要的返回值 } } ], imports: [HttpModule], }).compile(); service = module.get<AuthGuardService>(AuthGuardService); authService = module.get<AuthService>(AuthService); }); it('it should return true', async () => { // 替换成你实际要测试的AuthGuardService方法 expect(await service.yourTestMethod('1')).toBe(true); // 可额外验证find方法被正确调用 expect(authService.find).toHaveBeenCalledWith({ id: '1' }) }); }) - 临时加调试逻辑定位问题:如果修改后还是有问题,可以在mock方法中打印调用参数和返回值,确认方法是否被正确触发:
find: jest.fn((args) => { console.log('find被调用,参数:', args); return Promise.resolve({ id: '1' }) })
内容的提问来源于stack exchange,提问作者heliosk
相关产品推荐
相关产品推荐

