我正在尝试在打字稿中使用jest和模拟。ioredis
问题是我从中收到错误typescript:
tests/__mocks__/ioredis.ts(5,9): error TS2339: Property 'prototype' does not exist on type 'Redis''
Run Code Online (Sandbox Code Playgroud)
该代码确实有效,但我想解决这个错误。这是我的模拟:
// 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;
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
没有完美的解决方案。
首先定义一个带有prototype属性的接口:
interface IPrototype { prototype: any; }
Run Code Online (Sandbox Code Playgroud)
像这样使用IORedis可以访问原型和其他 Redis 方法。
(IORedis as IPrototype & Redis).prototype ...
Run Code Online (Sandbox Code Playgroud)
另一种选择可能是像这样声明你的 const:
interface IPrototype { prototype: any; }
type MyRedis = Redis & IPrototype;
const IORedis: MyRedis = jest.genMockFromModule<MyRedis>('ioredis');
Run Code Online (Sandbox Code Playgroud)
希望有帮助!
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           11684 次  |  
        
|   最近记录:  |