How do you simulate clicking on Ok
or Cancel
in a window.confirm using jest and 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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With