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

TypeScript中用Jest模拟IORedis遇prototype不存在错误

解决Jest模拟IORedis时的TypeScript报错问题

这个报错的根源是你对Redis类型的使用有误——你把模拟出来的类构造函数赋值给了Redis类型(这是实例类型),而prototype属性只属于类/构造函数本身,不属于实例,所以TypeScript会提示找不到prototype。

修正后的模拟代码

// tests/__mocks__/ioredis.ts
import { Redis } from 'ioredis';

// 这里要用 typeof Redis 表示Redis类的构造函数类型,而非实例类型
const IORedis: typeof Redis = jest.genMockFromModule('ioredis');

// 现在访问 prototype 就不会报错了
IORedis.prototype.hgetall = jest.fn().mockImplementation(async (key: string) => {
  // 这里可以写你的模拟逻辑,比如返回固定测试数据
  return { mockKey: 'mockValue' };
});

// 按需模拟其他Redis方法,比如set
IORedis.prototype.set = jest.fn().mockResolvedValue('OK');

export default IORedis;

更简洁的替代模拟方式

如果你的测试场景不需要完整复刻IORedis类的结构,也可以直接模拟实例的方法,避开prototype的类型问题:

// tests/__mocks__/ioredis.ts
export const Redis = jest.fn().mockImplementation(() => ({
  hgetall: jest.fn().mockResolvedValue({ mockKey: 'mockValue' }),
  set: jest.fn().mockResolvedValue('OK'),
  // 根据测试需求添加其他需要模拟的方法
}));

内容的提问来源于stack exchange,提问作者Tomer Amir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:50:34