Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do you simulate clicking on Ok or Cancel in a window.confirm using jest and enzyme?

like image 591
puerile Avatar asked Feb 11 '18 04:02

puerile


2 Answers

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.

like image 137
wgoodall01 Avatar answered Nov 20 '22 05:11

wgoodall01


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());
like image 28
François Zaninotto Avatar answered Nov 20 '22 04:11

François Zaninotto