Simulate clicking "Ok" or "Cancel" in a confirmation window using enzyme

Before the test, use jest.fn to mock 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

I use this trick all the time to mock out console.log to make sure errors/status is logged properly in certain conditions.


I'd advise against changing window.confirm, because this change "leaks" (i.e. it affects other tests). Instead, use jest's spyOn function to mock and restore window.confirm before and after the test:

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