Skip to content
Advertisement

Jest: How to undo a global mock for certain tests in a file

I want to mock Math.random for certain tests and use its original implementation for other tests. How can I achieve this? I’ve read about using jest.doMock and jest.dontMock, but I’ve bumped into a number of issues using them, like:

  • I seem to need require in order to use doMock and dontMock, but my project only uses ES6 modules for importing modules
  • Those functions also have issues taking in a global module like Math. I get an error when trying to use jest.doMock("Math.random"), which results in Cannot find module 'Math' from 'app.test.js'

I don’t necessarily need to use doMock and dontMock for my tests. They just seemed to be the closest thing I could find in the jest documentation to what I want to achieve. But I’m open to alternative solutions.

My function I want to test inside app.js…

JavaScript

Inside app.test.js…

JavaScript

Advertisement

Answer

Try this:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement