Hi i have a test in which i want to mock redis and then get this values.
I installed redis-mock
npm package and in jest test i want to do something like this:
import redis from 'redis-mock';
describe('test', () => {
const redisClient = redis.createClient();
redis.set('key', 'myKeyValue')
it ('should do sth', async () => {
const redisValue = redis.get('key');
console.log(redisValue);
expect(redisValue).toBe('myKeyValue');
})
)
But this doesn’t work. I got undefined
value. How to do something like this?
2
Answers
redis.set()
andredis.get()
methods are executed asynchronously, they accept a callback function. See the implementation ofredis.get()
and unit test example.You should get the value after the set operation completed.
test result:
It might out of the topic, but I just want to share how I test the redis with jest without installation of third party module as I
MOCK the redis
.This is my folder structure:
redis.js
redis.test.js
test result:
jest will inject redis from
__mocks__
directory, hence we do not use the real redis from node modules in unit testing.Hope it help!