yeahoffline / redis-mock

Node.js redis client mock
213 stars 111 forks source link

[WORKING] - How to make this work with redis 4 #209

Open jonit-dev opened 1 year ago

jonit-dev commented 1 year ago

In your jest.config.ts

add:

{
...
  setupFiles: ["./src/jest/jestInitialSetup.ts"],
}

jestInitialSetup.ts

import redis from "./redisV4Mock";
jest.mock("redis", () => redis);

redisV4Mock.ts

/* eslint-disable @typescript-eslint/explicit-function-return-type */
// redis-mock has not been updated for node-redis v4 yet, but the main changes
// in the API are camelCase names and promises instead of callback, so we can work around it.
// https://github.com/yeahoffline/redis-mock/issues/195
import redis from "redis-mock";
// @ts-expect-error Work-around redis-mock types reporting incorrectly as v4 redis.
import { RedisClient } from "@types/redis";
import { promisify } from "util";
const client = redis.createClient() as unknown as RedisClient;
const setEx = promisify(client.setex).bind(client);
const v4Client = {
  connect: () => undefined,
  get: promisify(client.get).bind(client),
  set: promisify(client.set).bind(client),
  del: promisify(client.del).bind(client),
  hSet: promisify(client.hset).bind(client),
  hGet: promisify(client.hget).bind(client),
  hDel: promisify(client.hdel).bind(client),
  flushAll: promisify(client.flushall).bind(client),
  setEx: promisify(client.setex).bind(client),
  expire: promisify(client.expire).bind(client),
  mGet: promisify(client.mget).bind(client),
  pSetEx: (key: string, ms: number, value: string) => setEx(key, ms / 1000, value),
  on: () => undefined,
  // Add additional functions as needed...
};
export default { ...redis, createClient: () => v4Client };

PS: customize redisV4Mocks with missing methods.

For example, if you start getting errors like:

    TypeError: this.redisManager.client.hGetAll is not a function

Just go to the redisV4Mock.ts and add the required method there.

PS2: This file was posted by someone else here.

ba2sik commented 1 month ago

Hi, I get TypeError: Cannot read properties of undefined (reading 'createClient'). Do you know why?