9

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.

Mr.
  • 9,429
  • 13
  • 58
  • 82

2 Answers2

12

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.)

Jan Legner
  • 644
  • 6
  • 13
12

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'));
Adam Eri
  • 889
  • 7
  • 13