Jest中的Stubbing窗口函数

Yan*_*Tay 15 javascript sinon jestjs

在我的代码中,我在"确定"单击window.confirm提示时触发回调,并且我想测试是否触发了回调.

sinon,我可以window.confirm通过以下方式存根函数:

const confirmStub = sinon.stub(window, 'confirm');
confirmStub.returns(true);
Run Code Online (Sandbox Code Playgroud)

有没有办法在Jest中实现这种存根?

And*_*rle 33

在开玩笑中,您可以使用覆盖它们global.

global.confirm = () => true
Run Code Online (Sandbox Code Playgroud)

在jest中,每个测试文件都在自己的进程中运行,您不必重置设置.

  • 我不相信您不必重置设置。我刚刚测试了这个并且可以确认当我设置`global.innerWidth`时,它在测试中持续存在。 (3认同)
  • 测试我的意思是测试文件 (2认同)

Bee*_*ice 11

为了消除模拟泄漏到其他测试的可能性,我使用了一次性模拟:

jest.spyOn(global, 'confirm' as any).mockReturnValueOnce(true);
Run Code Online (Sandbox Code Playgroud)


pom*_*421 9

我只是使用了Jest 模拟,它对我有用:

   it("should call my function", () => {
      // use mockImplementation if you want to return a value
      window.confirm = jest.fn().mockImplementation(() => true)

      fireEvent.click(getByText("Supprimer"))

      expect(window.confirm).toHaveBeenCalled()
}
Run Code Online (Sandbox Code Playgroud)