typescript - 属性 'prototype' 不存在

标签 typescript jestjs

我正在尝试在 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/

相关文章:

javascript - 在 gulp/typescript 生产构建中禁用 AngularJS 调试数据

reactjs - 如何在 TypeScript 中使用备用键正确键入对象?

angular - 共享运算符导致 Jest 测试失败

jestjs - 如何在 Jest 测试中处理 localStorage?

reactjs - React-Testing 库未在快照中呈现 Material-UI 对话框

javascript - 如何创建一个模拟来扩展 Jest 中的实际模块

javascript - lodash shuffle 是否提供均匀分布?

javascript - 如何阻止用户在 Angular 日期类型输入中输入 future 日期

arrays - 如何从 typescript 中的JSON中提取特定值

jestjs - Jest 中的 globalSetup、setupFiles、setupFilesAfterEnv 和 beforeAll 有什么区别,它们的具体用途是什么?