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 = {
my_constant1: "test",
my_constant2: "best",
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: {
      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.


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