V
V
Vladimir Golub2020-03-17 16:55:36
JavaScript
Vladimir Golub, 2020-03-17 16:55:36

What is the best way to write a test for a controller with Redis?

There is a controller in which the user is logged out of the system.
// controllers/auth/signOut

const redisModel = require('../../models/redis');

module.exports = async (req, res) => {
  const user = req.user;

  // check in redis id

  const checkInRedis = await redisModel.get(`id.${ user.id }`);

  // if exist, delete id

  if ( checkInRedis ) {
    redisModel.del(`id.${ user.id }`)
  }

  res.status(200).json({ result: 'ok' })
};


// models/redis
const redis = require('redis');
const set =   require('./set');
const get =   require('./get');
const del =   require('./del');

const REDIS_PORT = process.env.REDIS_PORT || 6379;

const clientRedis = process.env.REDIS_TEST ?  redis.createClient(REDIS_PORT);

module.exports = {
  set: set(clientRedis),
  get: get(clientRedis),
  del: del(clientRedis)
};


// models/redis/get
module.exports = clientRedis => key => {
  return new Promise((resolve, reject) => {
    clientRedis.get(key, (err, reply) => {
      if (err) reject(err);

      resolve(reply);
    })
  });
};

Similarly for del

Found package for mock redis.
https://www.npmjs.com/package/redis-mock

How to apply it correctly in this case
require('dotenv').config();

const express = require('express');
const request = require('supertest');
const bodyParser  = require('body-parser');
const redis  = require('redis-mock');

const auth = require('../../../../server/controllers/auth');
const { i18next, i18nextMiddleware } = require('../../../i18n-server');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(i18nextMiddleware);

app.post(
  '/',
  (req, res, next) => {
    if (req.body.id && req.body.type) {
      req.user = {
        id: req.body.id,
        type: req.body.type
      };
    }

    next();
  },
  auth.signOut
);

describe('signOut', () => {
  it('success', done => {
    i18next.on('initialized', () => {
      request(app)
        .post('/')
        .set('Accept-Language', 'en')
        .type('application/x-www-form-urlencoded')
        .send({
          id: 1,
          type: 'manager'
        })
        .end((err, res) => {
          if (err) return done(err);

          done();
        });
    });
  })
});


Introduce a variable like process.env.REDIS_TEST and change the package when creating a redis client?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Golub, 2020-03-17
@RazerVG

You need to connect mock

require('dotenv').config();

const express     = require('express');
const request     = require('supertest');
const bodyParser  = require('body-parser');
const redisMock   = require('redis-mock');
const redis       = require('redis');

const auth = require('../../../../server/controllers/auth');
const { i18next, i18nextMiddleware } = require('../../../i18n-server');

jest.spyOn(redis, 'createClient').mockImplementation(redisMock.createClient);

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(i18nextMiddleware);

app.post(
  '/',
  (req, res, next) => {
    if (req.body.id && req.body.type) {
      req.user = {
        id: req.body.id,
        type: req.body.type
      };
    }

    next();
  },
  auth.signOut
);

describe('signOut', () => {
  it('success', done => {
    i18next.on('initialized', () => {
      request(app)
        .post('/')
        .set('Accept-Language', 'en')
        .type('application/x-www-form-urlencoded')
        .send({
          id: 1,
          type: 'manager'
        })
        .end((err, res) => {
          if (err) return done(err);

          expect(res.status).toBe(200);
          expect(res.body.result).toBe('ok');

          done();
        });
    });
  });

  afterAll(() => {
    redis.closeInstance();
  });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question