用 Jest 模拟 JavaScript Math.random 不起作用

尤金·苏尼克

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 文件中即可。

脚本.js

Math.random();

脚本.spec.js

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

<html lang="en">
<body>
<p>title</p>
<script src="script.js"></script>
</body>
</html>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章