如何用Jest模拟Mongoose同一find方法的链式调用?
解决NestJS中Mongoose同一方法链式调用的单元测试模拟问题
核心思路
Mongoose的链式调用依赖方法返回Query对象(包含后续可调用的方法),所以要创建递归的Mock对象,让find方法每次被调用时都返回自身,同时按需注入exec等方法的返回值,以此支持连续链式调用。
具体实现步骤
构建递归Mock模型
定义Mock对象,让find方法返回自身,exec返回预设测试数据。如果有其他链式方法(如sort、limit),也可同步添加并返回自身:const mockNotesModel = { find: jest.fn().mockReturnThis(), exec: jest.fn().mockResolvedValue([{ id: '1', author: 'test', text: 'test note' }]), };在测试模块中注入Mock
在测试模块初始化时,用Mock对象替换原始Mongoose Model:beforeEach(async () => { const moduleRef = await Test.createTestingModule({ providers: [ NotesQueryService, { provide: getModelToken(Note.name), useValue: mockNotesModel }, ], }).compile(); service = moduleRef.get<NotesQueryService>(NotesQueryService); });验证链式调用的调用细节
在测试用例中,调用目标方法后,通过jest的断言方法验证find的调用次数与参数:it('when request filter by body then filter it', async () => { const query = { author: 'test', likeText: 'note' }; const result = await service.findByAuthorAndLikeText(query); // 断言find被调用两次,且每次参数匹配过滤条件 expect(mockNotesModel.find).toHaveBeenCalledTimes(2); expect(mockNotesModel.find).toHaveBeenNthCalledWith(1, { author: query.author }); expect(mockNotesModel.find).toHaveBeenNthCalledWith(2, { text: { $regex: query.likeText, $options: 'i' } }); expect(result).toEqual([{ id: '1', author: 'test', text: 'test note' }]); });动态调整返回值(可选)
如果需要不同测试场景返回不同数据,可在对应用例中重新mockexec的返回结果:mockNotesModel.exec.mockResolvedValueOnce([{ id: '2', author: 'test', text: 'another note' }]);
关键注意事项
- 所有链式方法必须返回Mock对象本身(
mockReturnThis()),才能支持连续调用。 - 使用
toHaveBeenNthCalledWith是验证同一方法多次链式调用参数的核心方式。
内容的提问来源于stack exchange,提问作者Jose Luiz Junior
相关产品推荐
相关产品推荐

