使用enzyme模拟在确认窗口中点击“确定”或“取消”按钮

18

如何在使用Jest和Enzyme的过程中模拟点击窗口确认框中的OkCancel按钮?


你能在模拟中返回true/false吗?这些是确认对话框的返回值。 - Sterling Archer
这可能会有所帮助 - Aniket Sahrawat
@AniketSahrawat 我不使用 sinon,只用 enzyme,但还是谢谢你提供的链接。 - puerile
@SterlingArcher 是的,所以我最终采用了答案中的方法。谢谢。 - puerile
2个回答

21

在测试之前,使用 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,以确保在某些条件下错误/状态被正确记录。


是的,这就是我最终做的事情,因为我找不到任何点击确认对话框的方法。谢谢。 - puerile

20

我建议不要更改window.confirm,因为这个更改会"泄露"(即影响其他测试)。相反,使用jest的spyOn函数在测试前后模拟和恢复window.confirm

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接