close

How to mock an exported const in jest

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to mock an exported const in jest in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to mock an exported const in jest ?

  1. How to mock an exported const in jest

    to mock an exported const in jest
    // foo.js export const foo = true; // could be expression as well // spec file import * as constants from './foo' Object.defineProperty(constant, 'foo', {value: 1})
    For functions:
    Object.defineProperty(store, 'doOneThing', {value: jest.fn()})

  2. How to mock an exported const in jest

    to mock an exported const in jest
    // foo.js export const foo = true; // could be expression as well // spec file import * as constants from './foo' Object.defineProperty(constant, 'foo', {value: 1})
    For functions:
    Object.defineProperty(store, 'doOneThing', {value: jest.fn()})

Method 1

Since we can’t override/mock the value directly. we can use the below hack

// foo.js
export const foo = true; // could be expression as well

// spec file
import * as constants from './foo'

Object.defineProperty(constant, 'foo', {value: 1})

For functions:

Object.defineProperty(store, 'doOneThing', {value: jest.fn()})

Method 2

I solved this by initializing constants from ContstantsFile.js in reducers. And placed it in redux store. As jest.mock was not able to mock the contstantsFile.js

constantsFile.js
-----------------
const MY_CONSTANTS = {
MY_CONSTANT1: "TEST",
MY_CONSTANT2: "BEST",
};
export defualt MY_CONSTANTS;

reducers/index.js
-----------------
import MY_CONST from "./constantsFile";

const initialState = {
...MY_CONST
}
export const AbcReducer = (state = initialState, action) => {.....}

ABC.jsx
------------
import { useSelector } from 'react-redux';
const ABC = () => {
const const1 = useSelector(state) => state. AbcReducer. MY_CONSTANT1:
const const2 = useSelector(state) => state. AbcReducer. MY_CONSTANT2:
.......

Now we can easily mock the store in test.jsx and provide the values to constant that we want.

Abc.text.jsx
-------------
import thunk from 'redux-thunk';
import configureMockStore from 'redux-mock-store';

describe('Abc mock constants in jest', () => {
const mockStore = configureMockStore([thunk]);
let store = mockStore({
   AbcReducer: {
      MY_CONSTANT1 ="MOCKTEST",
      MY_CONSTANT2 = "MOCKBEST",
   }
});

test('your test here', () => { .....

Now when the test runs it will always pick the constant value form mock store

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment