我正在尝试在 typescript 中使用 jest
和 mock ioredis
。
问题是我从 typescript
收到错误:
tests/__mocks__/ioredis.ts(5,9): error TS2339: Property 'prototype' does not exist on type 'Redis''
代码确实有效,但我想解决这个错误。 这是我的模拟:
// tests/__mocks__/ioredis.ts
import { Redis } from 'ioredis';
const IORedis: Redis = jest.genMockFromModule<Redis>('ioredis');
IORedis.prototype.hgetall = jest.fn().mockImplementation(async (key: string) => {
// Some mock implementation
});
module.exports = IORedis;
我做错了什么?
最佳答案
没有完美的解决方案。
首先定义一个带有原型(prototype)属性的接口(interface):
interface IPrototype { prototype: any; }
像这样使用 IORedis 可以访问原型(prototype)和其他 Redis 方法。
(IORedis as IPrototype & Redis).prototype ...
另一种选择可能是这样声明您的常量:
interface IPrototype { prototype: any; }
type MyRedis = Redis & IPrototype;
const IORedis: MyRedis = jest.genMockFromModule<MyRedis>('ioredis');
希望对您有所帮助!
关于typescript - 属性 'prototype' 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50215073/