Accepted answer

This example will work if you compile ES6 modules syntax into ES5, because in the end, all module exports belong to the same object, which can be modified.

import { allowThrough } from './allowThrough';
import { ENABLED } from './constants';
import * as constants from './constants';

describe('allowThrough', () => {
    test('success', () => {
        constants.ENABLED = true;

        expect(allowThrough({ value: 1 })).toBe(true);

    test('fail, ENABLED === false', () => {
        constants.ENABLED = false;

        expect(allowThrough({ value: 1 })).toBe(false);

Alternatively, you can switch to raw commonjs require function, and do it like this with the help of jest.mock(...):

const mockTrue = { ENABLED: true };
const mockFalse = { ENABLED: false };

describe('allowThrough', () => {
    beforeEach(() => {

    test('success', () => {
        jest.mock('./constants', () => mockTrue)
        const { ENABLED } = require('./constants');
        const { allowThrough } = require('./allowThrough');

        expect(allowThrough({ value: 1 })).toBe(true);

    test('fail, ENABLED === false', () => {
        jest.mock('./constants', () => mockFalse)
        const { ENABLED } = require('./constants');
        const { allowThrough } = require('./allowThrough');

        expect(allowThrough({ value: 1 })).toBe(false);


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

const MY_CONSTANTS = {
export defualt MY_CONSTANTS;

import MY_CONST from "./constantsFile";

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

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.

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: {

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

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


Instead of Jest and having trouble with hoisting etc. you can also just redefine your property using "Object.defineProperty"

It can easily be redefined for each test case.

This is a pseudo code example based on some files I have:

From localization file:

export const locale = 'en-US';

In another file we are using the locale:

import { locale } from 'src/common/localization';
import { format } from 'someDateLibrary';

// 'MMM' will be formatted based on locale
const dateFormat = 'dd-MMM-yyyy';

export const formatDate = (date: Number) => format(date, dateFormat, locale)

How to mock in a test file

import * as Localization from 'src/common/localization';
import { formatDate } from 'src/utils/dateUtils';

describe('format date', () => {
        test('should be in Danish format', () => {
            Object.defineProperty(Localization, 'locale', {
                value: 'da-DK'
        test('should be in US format', () => {
            Object.defineProperty(Localization, 'locale', {
                value: 'en-US'


One of the way for mock variables is the follow solution:

For example exists file ./constants.js with constants:

export const CONSTATN_1 = 'value 1';
export const CONSTATN_2 = 'value 2';

There is also a file of tests ./file-with-tests.spec.js in which you need to do mock variables. If you need to mock several variables you need to use jest.requireActual to use the real values of the remaining variables.

jest.mock('./constants', () => ({
  CONSTATN_1: 'mock value 1',

If you need to mock all variables using jest.requireActual is optional.

jest.mock('./constants', () => ({
  CONSTATN_1: 'mock value 1',
  CONSTATN_2: 'mock value 2'


The most common scenario I needed was to mock a constant used by a class (in my case, a React component but it could be any ES6 class really).

@Luke's answer worked great for this, it just took a minute to wrap my head around it so I thought I'd rephrase it into a more explicit example.

The key is that your constants need to be in a separate file that you import, so that this import itself can be stubbed/mocked by jest.

The following worked perfectly for me.

First, define your constants:

// src/my-component/constants.js

const MY_CONSTANT = 100;

export { MY_CONSTANT };

Next, we have the class that actually uses the constants:

// src/my-component/index.jsx

import { MY_CONSTANT } from './constants';

// This could be any class (e.g. a React component)
class MyComponent {
  constructor() {
    // Use the constant inside this class
    this.secret = MY_CONSTANT;
    console.log(`Current value is ${this.secret}`);

export default MyComponent

Lastly, we have the tests. There's 2 use cases we want to handle here:

  1. Mock the generate value of MY_CONSTANT for all tests inside this file
  2. Allow the ability for a specific test to further override the value of MY_CONSTANT for that single test

The first part is acheived by using jest.mock at the top of your test file.

The second is acheived by using jest.spyOn to further spy on the exported list of constants. It's almost like a mock on top of a mock.

// test/components/my-component/index.js

import MyComponent from 'src/my-component';
import allConstants from 'src/my-component/constants';

jest.mock('src/my-component/constants', () => ({
  get MY_CONSTANT () {
    return 30;

it('mocks the value of MY_CONSTANT', () => {
  // Initialize the component, or in the case of React, render the component
  new MyComponent();

  // The above should cause the `console.log` line to print out the 
  // new mocked value of 30

it('mocks the value of MY_CONSTANT for this test,', () => {
  // Set up the spy. You can then use any jest mocking method
  // (e.g. `mockReturnValue()`) on it
  const mySpy = jest.spyOn(allConstants, 'MY_CONSTANT', 'get')

  new MyComponent();

  // The above should cause the `console.log` line to print out the 
  // new mocked value of 15


Facing the same issue, I found this blog post very useful, and much simpler than @cyberwombat use case :

// esModule.js
export default 'defaultExport';
export const namedExport = () => {};
// esModule.test.js
jest.mock('./esModule', () => ({
  __esModule: true, // this property makes it work
  default: 'mockedDefaultExport',
  namedExport: jest.fn(),

import defaultExport, { namedExport } from './esModule';
defaultExport; // 'mockedDefaultExport'
namedExport; // mock function


For me the simplest solution was to redefine the imported object property, as decribed here:

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

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

Object.defineProperty(constant, 'foo', {value: 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()})


Thanks to @Luke I was able to expand on his answer for my needs. I had the requirements of:

  • Only mocking certain values in the file - not all
  • Running the mock only inside a single test.

Turns out that doMock() is like mock() but doesn't get hoisted. In addition requireActual() can be used to grab original data.

My config.js file - I need to mock only part of it

export const SOMETHING = 'blah'
export const OTHER = 'meh'

My test file

// import { someFunc } from  'some/file' // This won't work with doMock - see below
describe('My test', () => {

  test('someFunc() does stuff', async () => {

    // Here I mock the config file which gets imported somewhere deep in my code
    jest.doMock('config.js', () => {

      // Grab original
      const originalModule = jest.requireActual('config')

      // Return original but override some values
      return {
        __esModule: true, // Depends on your setup
        SOMETHING: 'boom!'

    // Because `doMock` doesn't get hoisted we need to import the function after
    const { someFunc } = await import(

    // Now someFunc will use the original config values but overridden with SOMETHING=boom!
    const res = await someFunc()

Depending on other tests you may also need to use resetModules() somewhere such as beforeAll or afterAll.



Unfortunately none of the posted solutions worked for me or to be more precise some did work but threw linting, TypeScript or compilation errors, so I will post my solution that both works for me and is compliant with current coding standards:

// constants.ts
// configuration file with defined constant(s)
export const someConstantValue = true;
// module.ts
// this module uses the defined constants
import { someConstantValue } from './constants';

export const someCheck = () => someConstantValue ? 'true' : 'false';
// module.test.ts
// this is the test file for module.ts
import { someCheck } from './module';

// Jest specifies that the variable must start with `mock`
const mockSomeConstantValueGetter = jest.fn();
jest.mock('./constants', () => ({
  get someConstantValue() {
    return mockSomeConstantValueGetter();

describe('someCheck', () => {
  it('returns "true" if someConstantValue is true', () => {

  it('returns "false" if someConstantValue is false', () => {


There is another way to do it in ES6+ and jest 22.1.0+ thanks to getters and spyOn.

By default, you cannot spy on primitive types like boolean or number. You can though replace an imported file with your own mock. A getter method still acts like a primitive member but allows us to spy on it. Having a spy on our target member you can basically do with it whatever you want, just like with a jest.fn() mock.

Below an example

// foo.js
export const foo = true; // could be expression as well
// subject.js
import { foo } from './foo'

export default () => foo
// subject.spec.js
import subject from './subject'

jest.mock('./foo', () => ({
  get foo () {
    return true // set some default value

describe('subject', () => {
  const mySpy = jest.spyOn(subject.default, 'foo', 'get')

  it('foo returns true', () => {

  it('foo returns false', () => {

Read more in the docs.

Related Query

More Query from same tag