You need to enable JavaScript to run this app. 用Jest测试NestJS的MongoDB服务时遇find方法不存在报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

用Jest测试NestJS的MongoDB服务时遇find方法不存在报错如何解决

报错根因

你的核心问题有三个:

  1. 给Nest注入的Mongoose模型mock是空对象{},根本没有实现find、exec这些实际调用的方法,你在测试外层单独声明的find、findOne等jest mock实例,完全没有和注入的模型关联,属于两套独立的对象,服务调用的时候自然找不到对应方法。
  2. 测试用例逻辑和实际服务逻辑不匹配:服务的get方法用的是find查询,但你在测试里给不存在的场景预设的是findOne的返回值,根本不会触发你写的判断逻辑,自然达不到预期测试效果。
  3. 异步断言写法错误:你原来写的const response = await ...; expect(response).toThrow(...)是无效的,如果方法执行抛错,代码会在await的位置直接中断,根本不会走到拿到response的步骤,自然断言不到异常。
正确实现方式

核心mock逻辑

  • 注入到测试模块的Mongoose模型mock,必须和测试用例里操控的jest mock是同一个引用,不能割裂。
  • 适配Mongoose的链式查询结构:find()调用后不会直接返回最终结果,而是返回一个挂载了exec()方法的查询对象,只有调用exec()才会返回查询的Promise值,mock的时候要顺着这个链路实现。
  • 修正异步断言的写法:判断异步方法抛错,要把await放在expect内部搭配.rejects使用,不能在await拿到返回值后再断言抛错,那样根本捕获不到实际抛出的异常。

修正后的完整测试代码

import { Test } from '@nestjs/testing';
import { QuestionsService } from './questions.service';
import { getModelToken } from '@nestjs/mongoose';
import { NotFoundException } from '@nestjs/common';
import { QuestionStatus } from './schemas/question.schema';

// 模拟符合Question结构的测试数据
const testQuestion = {
  createdBy: { id: 1, name: 'test user' },
  entityId: 1,
  entityType: 'announcement',
  status: QuestionStatus.ACTIVE,
};

describe('QuestionsService', () => {
  let questionService: QuestionsService;
  // 统一声明模型用到的find方法mock
  let findMock: jest.Mock;

  beforeEach(async () => {
    // 初始化find的mock返回结构,匹配Mongoose链式调用规则
    findMock = jest.fn().mockReturnValue({
      exec: jest.fn(),
    });

    const moduleRef = await Test.createTestingModule({
      providers: [
        QuestionsService,
        {
          provide: getModelToken('Question'),
          useValue: {
            find: findMock,
            // 后续如果用到其他Mongoose方法,直接在这里补对应的mock即可
            // findOne: jest.fn(),
            // findOneAndUpdate: jest.fn(),
          },
        },
      ],
    }).compile();

    questionService = moduleRef.get<QuestionsService>(QuestionsService);
  });

  it('should be defined', () => {
    expect(questionService).toBeDefined();
  });

  describe('when getting a question by entity info', () => {
    describe('and no matching question exists', () => {
      it('should throw a NotFound exception', async () => {
        // 预设查询返回空结果
        findMock().exec.mockResolvedValue([]);

        // 正确的异步抛错断言写法
        await expect(
          questionService.get('announcement', 9136500000)
        ).rejects.toThrow(NotFoundException);
      });
    });

    describe('and matching question exists', () => {
      it('should return the matched question data', async () => {
        // 预设查询返回带测试数据的结果集
        findMock().exec.mockResolvedValue([testQuestion]);

        const result = await questionService.get('announcement', 1);
        expect(result).toEqual({ data: [testQuestion] });
        // 可补充断言查询参数是否符合预期
        expect(findMock).toHaveBeenCalledWith(
          {
            entityType: 'announcement',
            entityId: 1,
            status: QuestionStatus.ACTIVE,
          },
          { answers: 0 },
          {
            sort: { _id: -1 },
            limit: 1,
          }
        );
      });
    });
  });
});

补充注意点

  • 不要在mockResolvedValue外面再套Promise.resolve(),这个方法本身就会返回resolve状态的Promise,套了属于冗余代码。
  • 如果后续服务用到了其他Mongoose方法,直接在注入的useValue对象上补充对应jest mock即可,不要在测试外层定义独立的mock变量,避免和注入对象脱节。
  • 只要是带.exec()的Mongoose查询链路,mock的时候必须顺着链路返回对应方法,不能直接让查询方法返回最终值,否则会触发exec is not a function的同类报错。

内容的提问来源于stack exchange,提问作者Marcus Christiansen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.20 02:45:02