skip to Main Content

I have the following file that connect to a redis database: index.js

const redis = require('redis');
const logger = require('../logger');
const config = require('../env');

const client = redis.createClient({
    host: config.redis.host,
    port: config.redis.port
});

const connect = () => {
    client.on('connect', () => {
        logger.info(`Redis connected on port: ${client?.options?.port}`);
    });
    client.on('error', err => {
        logger.error(`500 - Could not connect to Redis: ${err}`);
    });
};

const close = () => {
    client.quit();
};

module.exports = { connect, close, client };

And a helper file containing some Redis functionalities:

const util = require('util');
const { client } = require('./index.js');

const set = ({ key, data, mode, expiresIn }) => {
    client.set(key, data, mode, expiresIn);
};

const get = key => {
    client.get = util.promisify(client.get);
    return client.get(key);
};

const remove = key => {
    client.del(key);
};

const getKeys = keyPattern => {
    client.keys = util.promisify(client.keys);
    return client.keys(keyPattern);
};

module.exports = { set, get, remove, getKeys };

Now I want to test these functionalities with Jest, should I mock the Redis in mocks folder ? or just create a separate database for the test environment to test the functionalities?

2

Answers


  1. I think this can be a subjective issue. Firstly it depends on what types of testing you want to carry out. If it is unit testing, I would consider mocking the Redis service. Some developers look at unit testing as at the method or function level i.e. the method is the unit to test. But what a unit is can also be subjective. Service classes which expose limited public methods could be also considered the unit. If you are running integration tests, I would strongly consider using an actual redis instance. In previous roles we used to use docker-compose to launch all our service dependencies to run local integration, but again that depends on the complexity of your dependencies. In my current role, integration testing is carried out against mocks. IMO it is a question which will get a subjective answer.

    Login or Signup to reply.
  2. As jeeves said, i’d agree its subjective. I am in the process of writing Jest tests for my redis service, but from the action – so i am checking that my action gets and sets from a mock redis.

    Explicitly on your code above there is very little logic taking place, so i would suggest that tests were not needed – else you would be pretty close to testing that promisify / redis itself is working, and we need to assume that their code is ok.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search