redis node js mock and get values in test

Viewed 2093

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() and redis.get() methods are executed asynchronously, they accept a callback function. See the implementation of redis.get() and unit test example.

You should get the value after the set operation completed.

import redis from 'redis-mock';

describe('test', () => {
  it('should do sth', (done) => {
    const redisClient = redis.createClient();
    redisClient.set('key', 'myKeyValue', () => {
      redisClient.get('key', (err, redisValue) => {
        console.log(redisValue);
        expect(redisValue).toBe('myKeyValue');
        done();
      });
    });
  });
});

test result:

 PASS  examples/66336108/index.test.ts
  test
    ✓ should do sth (10 ms)

  console.log
    myKeyValue

      at examples/66336108/index.test.ts:8:17

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.277 s, estimated 2 s

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:

- node_modules
- tests
  - __mocks__
    - redis.js
- unit
  - redis.test.js
- package.json

redis.js

module.exports = {
    createClient() {
        return {
            __data: {},
            get data() {
                return this.__data;
            },
            set data(data) {
                this.__data = data;
            },
            get(key) {
                return this.data[key];
            },
            set(key, value) {
                this.data[key] = value;
            }
        }
    }
}

redis.test.js

const redis = require('redis');

describe('test', () => {
  const redisClient = redis.createClient();
  redisClient.set('key', 'myKeyValue');

  it ('should do sth', async () => {
     const redisValue = redisClient.get('key');
     console.log(redisValue);
     expect(redisValue).toBe('myKeyValue');
  });
});

test result:

 PASS  tests/unit/redis.test.js
  test
    ✓ should do sth (10 ms)

  console.log
    myKeyValue

      at Object.<anonymous> (tests/unit/redis.test.js:9:14)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.786 s
Ran all test suites.
Done in 1.31s.

jest will inject redis from __mocks__ directory, hence we do not use the real redis from node modules in unit testing.

Hope it help!

Related