Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to mock node-redis using jest

i am using jest and trying to mock node-redis using redis-mock.

// redis.js

const redis = require("redis");
const client = redis.createClient({ host: '127.0.0.1', port: 6379 });

// redis.test.js

const redisMock = require("redis-mock");

describe("redis", () => {
  jest.doMock("redis", () => jest.fn(() => redisMock));
  const redis = require("./redis");
});

when i run the tests, i get an error

TypeError: redis.createClient is not a function

feels to me that i am doing something wrong when using jest.doMock().

would appreciate your assistance.

like image 299
Mr. Avatar asked May 08 '26 11:05

Mr.


2 Answers

The following works for me:

import redis from 'redis-mock'
jest.mock('redis', () => redis)

I do not include the redis library in the test at all, but I include it only in the file which contains the tested class. (The file with tested class is, of course, included in the test file.)

like image 140
Jan Legner Avatar answered May 10 '26 00:05

Jan Legner


If you are using jest, the switching of the mock and the actual implementation is possible automatically. Works great for CI.

jest.config.js

module.exports = {
    // other properties...
    setupFilesAfterEnv: ['./jest.setup.redis-mock.js'],
};

jest.setup.redis-mock.js

jest.mock('redis', () => jest.requireActual('redis-mock'));
like image 22
Adam Eri Avatar answered May 10 '26 00:05

Adam Eri