在测试之前,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以确保在某些条件下正确记录错误/状态.
我建议不要更改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)
| 归档时间: |
|
| 查看次数: |
2200 次 |
| 最近记录: |