How to mock a module in jest testing

A simple example to understand how to mock a module in jest

kob003
1 min readJan 22, 2021

we will be using ‘uuid’ module for our example;

Suppose we have a setId.js action file:

import {v4 as uuidv4} from "uuid";const setId = () => (dispatch) => {                          
const id = uuidv4();
dispatch({
type:'SET_ID',
id
});
};

we want to test this action file. So this will be our setId.test.js( assuming you have a understanding of creating a mock store):

import { v4 as uuidv4 } from "uuid";
import thunk from "redux-thunk";
import configureMockStore from "redux-mock-store";
/** mock uuid */
jest.mock("uuid");
/** mock-store */
const createMockStore = configureMockStore([thunk]);
const defaultState = [];
const store = createMockStore(defaultState);
/* our test*/
test('should set id',() => {

/* This line is where we will desribe what uuidv4 should do. */
uuidv4.mockImplementation(() => "uuid123");
/* Now whenever we call uuidv4() inside our test, we will be getting 'uuid123' as the returned value. Thus, we get constant uuid value for our testing purpose */
const id = uuidv4(); /* Here id = 'uuid123', as explained above*//* dispatch the action */
store.dispatch(setId());
/* expect */
expect(store.getActions()).toEqual([
{
type: 'SET_ID',
payload: { msg: "test", alertType: "test", id },
},
]);

--

--