mercredi 24 juin 2020

How do you mock a named exports constructor and functions of an external library with Jest?

I have seen similar questions but nothing I have seen in the documentation or stackoverflow describes what I am trying to do. I am new to javascript and just started using jest, I have read through the jest documentation but I have not seen an example that mocks a named export of an external library. The library I am trying to mock is rate-limiter-flexible. I want to mock the named export RateLimiterRedis. I need to mock a couple of RateLimiterRedis functions, including get, consume, and delete.

For example when I mocked a function from redis all I had to do was:

import redis from 'redis';
jest.mock('redis', () => {
    return { createClient: jest.fn()};
});

When I try:

jest.mock('rate-limiter-flexible', () => {
    return jest.fn().mockImplementation(() => {
        return { RateLimiterRedis: { get: mockGet } }
    });
});

I get: TypeError: _rateLimiterFlexible.RateLimiterRedis is not a constructor

When I try:

jest.mock('rate-limiter-flexible', () => {
    return { RateLimiterRedis: () => {}}
});

I get: TypeError: limiter.get is not a function
So it recognizes the constructor but I need to add the functions.

I have tried:

jest.mock('rate-limiter-flexible', () => {
    return { RateLimiterRedis: () => {
        return jest.fn().mockImplementation(() => {
            return {
                get: mockGet
            }
        })
    },
            }
});

This also gives: TypeError: limiter.get is not a function

This is in my file I am trying to test:

const limiter = new RateLimiterRedis(opts);

I have also tried doMocking the named export itself (since mock hoists itself to the top) to no success

My question boils down to how can I mock a constructor of a class and that classes functions with jest, when that class is a named export of an external library? Any help is appreciated, thank you.

Aucun commentaire:

Enregistrer un commentaire