首页 > 解决方案 > 属性“原型”不存在

问题描述

我正在尝试在打字稿中使用jest和模拟。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;

我究竟做错了什么?

标签: typescriptjestjs

解决方案


没有完美的解决方案。

首先定义一个带有原型属性的接口:

interface IPrototype { prototype: any; }

像这样使用IORedis可以访问原型和其他 Redis 方法。

(IORedis as IPrototype & Redis).prototype ...

另一种选择可能是像这样声明你的 const :

interface IPrototype { prototype: any; }
type MyRedis = Redis & IPrototype;
const IORedis: MyRedis = jest.genMockFromModule<MyRedis>('ioredis');

希望有帮助!


推荐阅读