Math.random()
总是给出随机值而不是模拟值。
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();
});
});
索引.html
<html lang="en">
<body>
<p>title</p>
<script>
// not showing mocked value
console.log(Math.random())
</script>
</body>
</html>
加载时是否有可能创建一个新实例,因此没有选择模拟?足够有趣的嘲弄setInterval
作品。
也试过.mockImplementation(() => 0.123456789)
无济于事。
看起来模拟并没有延续到 JSDOM。为了解决这个问题,我个人建议将脚本拆分为自己的文件,然后对脚本文件运行测试,如下例所示。将它们拆分后,只需将脚本文件包含在 HTML 文件中即可。
Math.random();
describe("script.js", () => {
let spyOnMathRandom;
beforeEach(() => {
spyOnMathRandom = jest.spyOn(global.Math, 'random').mockReturnValue(1);
require('./script');
});
it("calls math random", () => {
expect(spyOnMathRandom).toReturnWith(1);
});
});
<html lang="en">
<body>
<p>title</p>
<script src="script.js"></script>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句