How you mock the 3rd party libraries’ function in Jest unit test

Mitsuhide Ohi
2 min readJan 14, 2019

--

Since the Jest has the capability to intercept the function call and return the mock data, it’s possible to let it return the arbitrary response in the unit test.

I will explain how you mock the 3rd party libraries’/node packages’ function in Jest by showing an example using the library called ioredis.

ioredis is the library providing the methods to store and get data on the Redis.

Intercept the function call

For this time, I will intercept the ioredis library’s get function’s and respond null always.

In order to create a mock for 3rd party library, create the .js file with the module name in __mocks__ directory in the root directory specified in Jest config.

This mock will works globally in the project.

/__mocks__/ioredis.js

In the file, create a mocked version of ioredis. Basically, pass the library name you want to mock in this function.

const IORedis = jest.genMockFromModule('ioredis')

And implement mock for the get function.

IORedis.prototype.get.mockImplementation((key, callback) => {
callback(null, null)
})

Suppose to pass error and response in this callback of the get. I set null for both as mock returning.
Since the expected inputs for the callback are differ by the functions, you need to refer to the interface for the function you wanted to mock to figure out this.

Lastly, export the modules.

module.exports = IORedis

So the complete code for /__mocks__/ioredis.js will be like this.

const IORedis = jest.genMockFromModule('ioredis')IORedis.prototype.get.mockImplementation((key, callback) => {
callback(null, IORedis.mockResponse.get.shift() || null)
})
module.exports = IORedis

Now you’re ready for the mock response for the get function in the ioredis node package in the test.
Every time the get function gets called in the testing function, null will be returned for both error and response of the callback.

--

--

Responses (1)