3 Ways to Mock Global Variables in Jest

There are many different ways to mock global variables in Jest. Here are three different ways you can mock global variables like Math.random or Date.now.

// Using the global object
global.document = {
  referrer: 'https://webtips.dev'
}

// Using a spy
jest.spyOn(Date, 'new').mockReturnValue(16565005947)

// Using Object.defineProperty
Object.defineProperty(Math, 'random', {
    value: () => 0.5
})
Copied to clipboard!

The first solution uses the global object on which you can reassign values to mock them. The overwrite only works for the current test suite and will not affect other tests.

Need to mock process.env in Jest?Β Check out this tutorial.

If you need to mock a global variable for all of your tests, you can use the setupFiles in your Jest config and point it to a file that mocks the necessary variables. This way, you will have the global variable mocked globally for all test suites.

module.exports = {
    setupFiles: ['<rootDir>/setup-mock.js']
}

// Inside setup-mock.js
global.document = {
    referrer: 'https://webtips.dev'
}
Mock global variables globally
Copied to clipboard!

In case you are running into issues using the global object, you can also use a spy with mockReturnValueΒ by passing the object as the first parameter, and the method as a string for the second parameter:

jest.spyOn(Date, 'new').mockReturnValue(16565005947)

// βœ… Passes
expect(Date.now()).toBe(16565005947)
Mock the return value of Date.now
Copied to clipboard!

Lastly, if none of the above solutions are suitable for you, you can also use Object.defineProperty similarly to jest.spyOn. It accepts a configuration object as the third parameter where you can set the value through the value property.

Object.defineProperty(Math, 'random', {
    value: () => 0.5,
    writable: true
})

// βœ… Passes
expect(Math.random()).toBe(0.5)
Mocks Math.random using Object.defineProperty
Copied to clipboard!

To avoid gettingΒ TypeError: Cannot redefine property, you will need to set writable to true on the property. This will enable the property to be redefinable.

JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in 5 hours.

Learn More

πŸ“š Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. β˜•

Get access Support us
Read more on
πŸŽ‰ Thank you for subscribing to our newsletter. x