Reputation: 1585
I am trying to use jest
and mock ioredis
in typescript.
The issue is that I am getting an error from typescript
that:
tests/__mocks__/ioredis.ts(5,9): error TS2339: Property 'prototype' does not exist on type 'Redis''
The code does work, but I would like to solve this error. Here is my mock:
// 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;
What am I doing wrong?
Upvotes: 6
Views: 12776
Reputation: 2139
If the type you need to extend is generic, you can use type variables when creating the union type.
interface IPrototype { prototype: any; }
type ExtendedType<A, B> = IPrototype & BasicType<A, B>;
Then you can cast using
(myvar as ExtendedType<any, any>).prototype
Upvotes: 1
Reputation: 4475
There is a no perfect solution.
First define a intereface with prototype property:
interface IPrototype { prototype: any; }
The use IORedis like this to have access to prototype and ohter Redis methods.
(IORedis as IPrototype & Redis).prototype ...
Another option might be to declare your const like this:
interface IPrototype { prototype: any; }
type MyRedis = Redis & IPrototype;
const IORedis: MyRedis = jest.genMockFromModule<MyRedis>('ioredis');
Hope that helps!
Upvotes: 6