node-redis icon indicating copy to clipboard operation
node-redis copied to clipboard

Provide an official mocking library for mocking Node-Redis in Jest tests

Open blagae opened this issue 2 years ago • 8 comments

Description

I am struggling to find a way to combine the modern Redis v4 client with the jest test framework.

This is my production code:

import redis from 'redis';
import config from './config';
import logger from './logger';

const redisClient = redis.createClient(config.redisConfig);
redisClient.on('error', (e) => logger.error(e));

(async () => {
  await redisClient.connect();
})();

export type RedisClient = typeof redisClient;
export default async () => {
  const clone = redisClient.duplicate();
  await clone.connect();
  return clone;
};

Some of my services of course use redis, and when I try to test them, the entire test suite usually fails at startup. This is a project that was migrated from plain JS to TS, from node-redis 3 to 4, and from mocha to jest.

Below are a few scenarios that don't work.

No config added:

FAIL lib/services/tests/area.spec.ts
  ● Test suite failed to run

    TypeError: Cannot read properties of undefined (reading 'createClient')

      4 |
    > 5 | const redisClient = redis.createClient(config.redisConfig);
        |                           ^

      at Object.createClient (lib/redis-client.ts:5:27)

Using the documented scenario with redis-mock:

in package.json

  "jest": {
    "setupFilesAfterEnv": [
      "./jest.setup.redis-mock.js"
    ]
  },

in jest.setup.redis-mock.js

import {jest} from '@jest/globals';
jest.mock('redis', () => jest.requireActual('redis-mock'));

Gives the error:

FAIL lib/services/tests/area.spec.ts
    TypeError: redisClient.connect is not a function

       8 | (async () => {
    >  9 |   await redisClient.connect();
         |                     ^
      10 | })();

      at connect (lib/redis-client.ts:9:21)
      at asyncGeneratorStep (lib/redis-client.ts:3:31)

Messing around in the jest setup file usually ends up with the entire library being undefined, etc.

blagae avatar Jun 22 '23 20:06 blagae