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 usedoMock
anddontMock
, 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 usejest.doMock("Math.random")
, which results inCannot 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
x
7
1
export function getRandomId(max) {
2
if (!Number.isInteger(max) || max <= 0) {
3
throw new TypeError("Max is an invalid type");
4
}
5
return Math.floor(Math.random() * totalNumPeople) + 1;
6
}
7
Inside app.test.js…
JavaScript
1
16
16
1
describe("getRandomId", () => {
2
const max = 10;
3
Math.random = jest.fn();
4
5
test("Minimum value for an ID is 1", () => {
6
Math.mockImplementationOnce(() => 0);
7
const id = app.getRandomId(max);
8
expect(id).toBeGreaterThanOrEqual(1);
9
});
10
11
test("Error thrown for invalid argument", () => {
12
// I want to use the original implementation of Math.random here
13
expect(() => getRandomId("invalid")).toThrow();
14
})
15
});
16
Advertisement
Answer
Try this:
JavaScript
1
21
21
1
describe("getRandomId", () => {
2
const max = 10;
3
let randomMock;
4
5
beforeEach(() => {
6
randomMock = jest.spyOn(global.Math, 'random');
7
});
8
9
test("Minimum value for an ID is 1", () => {
10
randomMock.mockReturnValue(0);
11
const id = getRandomId(max);
12
expect(id).toBeGreaterThanOrEqual(1);
13
});
14
15
test("Error thrown for invalid argument", () => {
16
// I want to use the original implementation of Math.random here
17
randomMock.mockRestore(); // restores the original (non-mocked) implementation
18
expect(() => getRandomId("invalid")).toThrow();
19
})
20
});
21