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

Jest Mock Mongoose方法时遇then/catch报错:Cannot read properties of null

问题分析与解决

错误原因

你遇到的Cannot read properties of null (reading 'then')错误,本质是mock的find方法返回值不是一个带有then方法的可执行对象(thenable)。Mongoose的find方法返回的是Query对象,它本身支持then/catch调用(属于thenable),但你当前mock的value可能是普通数组、null或其他非thenable类型,导致原代码调用.then()时触发报错。

解决方案

1. 正确Mock返回Thenable对象

确保mock的find方法返回一个能调用then的对象,以下两种方式任选其一:

方式一:用Promise.resolve模拟

// 定义模拟的请求数据
const mockRequestData = [
  { endpointId: 'test-id', deleted: false },
  { endpointId: 'test-id', deleted: true }
];

// mock find方法返回resolved的Promise
jest.spyOn(mockEndpointModel, 'find').mockResolvedValue(mockRequestData);

方式二:模拟Mongoose Query的Thenable结构

如果需要更贴近真实Mongoose Query的行为(比如支持链式调用),可以手动模拟then方法:

const mockRequestData = [
  { endpointId: 'test-id', deleted: false },
  { endpointId: 'test-id', deleted: true }
];

jest.spyOn(mockEndpointModel, 'find').mockReturnValue({
  then: (cb: (data: typeof mockRequestData) => void) => cb(mockRequestData),
  catch: (errCb: (err: Error) => void) => errCb
} as any);

2. 优化原函数写法(可选)

原函数中混用await和then/catch属于冗余写法,建议改成标准的async/await + try/catch结构,代码更清晰也更易测试:

async getByEndpointId(endpointId: string) {
  try {
    const requests = await this._requestModel.find({ endpointId });
    return requests.filter(req => !req.deleted);
  } catch (error) {
    console.log("One Error");
  }
}

内容的提问来源于stack exchange,提问作者Eduardo Moritz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:10:54