πŸ’‘ This page contain affiliate links. By making a purchase through them, we earn a commission at no extra cost to you.
3 Ways to Mock Global Variables in Jest

3 Ways to Mock Global Variables in Jest

How to work with Math.random and Date.now
Ferenc Almasi β€’ 2022 June 29 β€’ πŸ“– 2 min read
  • twitter
  • facebook

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.

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended