πŸ’‘ This page contain affiliate links. By making a purchase through them, we may 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 β€’ Read time 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.

Copied to clipboard! Playground
// 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
})

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.

Copied to clipboard! Playground
module.exports = {
    setupFiles: ['<rootDir>/setup-mock.js']
}

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

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:

Copied to clipboard!
jest.spyOn(Date, 'new').mockReturnValue(16565005947)

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

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.

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

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

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.

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.