How to clean-up / reset redis-mock in an Express Jest test?

I have an app which tallies the number of visits to the url. The tallying is done in Redis. I’m using redis-mock which simulates commands like INCR in memory.

The following test visits the page 3 times and expects the response object to report current as 3:

let app = require('./app');
const supertest = require("supertest");

jest.mock('redis', () => jest.requireActual('redis-mock'));

/* Preceeded by the exact same test */

it('should report incremented value on multiple requests', (done) => {
    const COUNT = 3;
    const testRequest = function (cb) { supertest(app).get('/test').expect(200, cb) };

    ], (err, results) => {
      if (err) console.error(err);

      const lastResponse = _.last(results).body;



The issue is that if I keep reusing app, the internal "redis" mock will continue getting incremented between tests.

I can side-step this a bit by doing this:

beforeEach(() => {
  app = require('./app');

Overwriting app seems to do the trick but isn’t there a way to clean-up the "internal" mocked module somehow between tests?

Source: JavaSript – Stack Overflow

November 7, 2021
Category : News
Tags: javascript | jestjs | mocking | node.js | redis

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.