【问题标题】:Stubbing window functions in JestJest 中的存根窗口函数
【发布时间】:2017-06-03 15:03:33
【问题描述】:

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

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

const confirmStub = sinon.stub(window, 'confirm');
confirmStub.returns(true);

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

【问题讨论】:

    标签: javascript sinon jestjs


    【解决方案1】:

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

    jest.spyOn(global, 'confirm' as any).mockReturnValueOnce(true);
    

    【讨论】:

      【解决方案2】:

      我刚刚使用了 Jest mock,它对我有用:

         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()
      }
      

      【讨论】:

        【解决方案3】:

        开玩笑地说,您可以使用 global 覆盖它们。

        global.confirm = () => true
        

        就像开玩笑一样,每个测试文件都在自己的进程中运行,您不必重置设置。

        【讨论】:

        • 我不认为您不必重置设置是真的。我刚刚对此进行了测试,可以确认当我设置 global.innerWidth 时,它在测试中仍然存在。
        • 测试是指测试文件
        猜你喜欢
        • 2017-12-28
        • 1970-01-01
        • 2014-05-07
        • 2019-01-15
        • 2016-07-14
        • 2018-07-11
        • 2018-08-10
        • 2022-01-19
        • 2023-04-09
        相关资源
        最近更新 更多