【问题标题】:Simulate clicking "Ok" or "Cancel" in a confirmation window using enzyme使用酶模拟在确认窗口中单击“确定”或“取消”
【发布时间】:2018-07-21 13:01:00
【问题描述】:

你如何模拟点击窗口中的OkCancel 使用玩笑和酶确认?

【问题讨论】:

  • 你能在模型上返回真/假吗?这些是确认对话框的返回
  • @AniketSahrawat 我不使用sinon,只使用enzyme,但感谢您提供的链接。
  • @SterlingArcher 是的,所以我最终在答案中做了。谢谢。

标签: javascript reactjs jestjs enzyme


【解决方案1】:

测试前,使用jest.fn模拟window.confirm

// with jest.fn, you can pass a function as the mock's implementation
// so pass something that returns `true` for yes, or `false` for no.
window.confirm = jest.fn(() => true) // always click 'yes'

// run your test code here

expect(window.confirm).toBeCalled() // or whatever assertions you want

我一直使用这个技巧来模拟 console.log 以确保在某些条件下正确记录错误/状态。

【讨论】:

  • 是的,这就是我最终要做的,因为我找不到任何方法来点击确认对话框。谢谢。
【解决方案2】:

我建议不要更改 window.confirm,因为此更改会“泄漏”(即它会影响其他测试)。而是使用 jest 的spyOn 函数在测试前后模拟和恢复window.confirm

let confirmSpy;
beforeAll(() => {
    confirmSpy = jest.spyOn(window, 'confirm');
    confirmSpy.mockImplementation(jest.fn(() => true));
});
afterAll(() => confirmSpy.mockRestore());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    相关资源
    最近更新 更多