skip to Main Content

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.

2

Answers


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

    Login or Signup to reply.
  2. 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'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search