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.
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.)
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With