在 Jest 中存根 window 函数
Stubbing window functions in Jest
在我的代码中,我在 "OK" 单击 window.confirm
提示时触发回调,我想测试是否触发了回调。
在 sinon
中,我可以通过以下方式存根 window.confirm
函数:
const confirmStub = sinon.stub(window, 'confirm');
confirmStub.returns(true);
有没有办法在 Jest 中实现这种存根?
开个玩笑,您可以使用 global
.
覆盖它们
global.confirm = () => true
开个玩笑,每个测试文件 运行 在其自己的进程中,您不必重置设置。
我刚刚使用了 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()
}
为了消除模拟泄漏到其他测试的可能性,我使用了一次性模拟:
jest.spyOn(global, 'confirm' as any).mockReturnValueOnce(true);
在我的代码中,我在 "OK" 单击 window.confirm
提示时触发回调,我想测试是否触发了回调。
在 sinon
中,我可以通过以下方式存根 window.confirm
函数:
const confirmStub = sinon.stub(window, 'confirm');
confirmStub.returns(true);
有没有办法在 Jest 中实现这种存根?
开个玩笑,您可以使用 global
.
global.confirm = () => true
开个玩笑,每个测试文件 运行 在其自己的进程中,您不必重置设置。
我刚刚使用了 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()
}
为了消除模拟泄漏到其他测试的可能性,我使用了一次性模拟:
jest.spyOn(global, 'confirm' as any).mockReturnValueOnce(true);