使用酶模拟确认窗口中的"确定"或"取消"

pue*_*ile 7 javascript reactjs jestjs enzyme

你如何模拟点击OkCancel在窗口中.使用jest和酶确认?

wgo*_*l01 8

在测试之前,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
Run Code Online (Sandbox Code Playgroud)

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


Fra*_*tto 8

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

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