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
相关产品推荐
相关产品推荐

