skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. I’m using :

    const RedisMock = require('ioredis-mock');
    jest.mock('ioredis', () => jest.requireActual('ioredis-mock'));
    
    const redis = new RedisMock({
                port: <same as in production>,
                host : <same as in production>,
                data: { 'Key:1': [JSON.stringify({"state":"INITIAL","recordingError":null})] ,
                        'Key:2': [JSON.stringify({"JSONVersionId":"1.0","agentTack":"11ebd1d4})] ,
           }
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search