You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Jest模拟Mongoose同一find方法的链式调用?

解决NestJS中Mongoose同一方法链式调用的单元测试模拟问题

核心思路

Mongoose的链式调用依赖方法返回Query对象(包含后续可调用的方法),所以要创建递归的Mock对象,让find方法每次被调用时都返回自身,同时按需注入exec等方法的返回值,以此支持连续链式调用。

具体实现步骤

  1. 构建递归Mock模型
    定义Mock对象,让find方法返回自身,exec返回预设测试数据。如果有其他链式方法(如sort、limit),也可同步添加并返回自身:

    const mockNotesModel = {
      find: jest.fn().mockReturnThis(),
      exec: jest.fn().mockResolvedValue([{ id: '1', author: 'test', text: 'test note' }]),
    };
    
  2. 在测试模块中注入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);
    });
    
  3. 验证链式调用的调用细节
    在测试用例中,调用目标方法后,通过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' }]);
    });
    
  4. 动态调整返回值(可选)
    如果需要不同测试场景返回不同数据,可在对应用例中重新mockexec的返回结果:

    mockNotesModel.exec.mockResolvedValueOnce([{ id: '2', author: 'test', text: 'another note' }]);
    

关键注意事项

  • 所有链式方法必须返回Mock对象本身(mockReturnThis()),才能支持连续调用。
  • 使用toHaveBeenNthCalledWith是验证同一方法多次链式调用参数的核心方式。

内容的提问来源于stack exchange,提问作者Jose Luiz Junior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 07:31:01