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

时间:2018-02-11 04:08:01

标签: javascript reactjs jestjs enzyme

如何使用jest和酶模拟在窗口中单击OkCancel

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:6)

我建议您不要更改window.confirm,因为此更改会“泄漏”(即会影响其他测试)。相反,在测试之前和之后,请使用jest的spyOn函数模拟并还原window.confirm

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