Math.random()
always giving random values instead of mocked ones.
index.test.js
jest.spyOn(global.Math, "random").mockReturnValue(0.123456789);
const html = fs.readFileSync(path.resolve(__dirname, "./index.html"), "utf8");
let dom;
let container;
describe("index.html", () => {
beforeEach(() => {
dom = new JSDOM(html, { runScripts: "dangerously" });
container = dom.window.document.body;
});
it("renders body paragraph", () => {
expect(container.querySelector("p")).toBeInTheDocument();
});
});
index.html
<html lang="en">
<body>
<p>title</p>
<script>
// not showing mocked value
console.log(Math.random())
</script>
</body>
</html>
Is it possible a new instance is created when loading hence mock isn't picked? Interesting enough mocking setInterval
works.
Also tried .mockImplementation(() => 0.123456789)
to no avail.