如何在使用Jest和Enzyme的过程中模拟点击窗口确认框中的Ok
或Cancel
按钮?
如何在使用Jest和Enzyme的过程中模拟点击窗口确认框中的Ok
或Cancel
按钮?
在测试之前,使用 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
,以确保在某些条件下错误/状态被正确记录。
我建议不要更改window.confirm
,因为这个更改会"泄露"(即影响其他测试)。相反,使用jest的spyOn
函数在测试前后模拟和恢复window.confirm
:
let confirmSpy;
beforeAll(() => {
confirmSpy = jest.spyOn(window, 'confirm');
confirmSpy.mockImplementation(jest.fn(() => true));
});
afterAll(() => confirmSpy.mockRestore());
sinon
,只用enzyme
,但还是谢谢你提供的链接。 - puerile