javascriptunit-testingjestjsioredis

Jest ioredis mock - Bind mock to module


In typescript, i have the following instantion of IoRedis.

import IoRedis from "ioredis";

const redis = new IoRedis({
    ...
});

While mocking in the test classes the following way. Decided to go with ioredis-mock, to solve this problem.

var IoRedis = require('ioredis-mock');
var ioRedis = new IoRedis({
    data: {
        ...
    },
});
jest.mock('ioredis', ioRedis);

Which results in an error.

TypeError: this._mockFactories.get(...) is not a function

I have tried alternative calls to mock ioredis, but have a hard time binding the test version of the mock to the one being resolved in my code. Mainly i think the new IoRedis is the culprit but my javascript experience is not sufficient to know which way to mock an import/require followed by an new keyword.


Solution

  • Based on the es-6-class-mocks, i found an approach that worked, mocking constructor on a class.

    var IoRedis = require('ioredis-mock');
    var ioRedis = new IoRedis({
        data: {
            cacheKey: cacheData
        },
    });
    jest.mock('ioredis', () => {
        return function () {
            return ioRedis
        };
    });
    

    This snippet can be used to mock ioredis, which i couldn't find online either in documentation or Stackoverflow.