Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock window.close() in React-testing-library

I have searched online but I didn't find a way to mock window.close() in react testing library or even in jest.

const handleClose = () => {
window.opener.location.reload()
window.close()
}

<Button
  data-test-id="close"
  onClick={handleClose}
/>

How do I achieve test case coverage for the onclick of button and window.close() and window.opener.location.reload() is covered

My test case is as follows:

const wrapper = render( <CloseButton />);
const windowSpy = jest.spyOn(global, 'window', 'get');

const { queryByTestId } = wrapper;
fireEvent.click(queryByTestId('close');
expect(windowSpy.opener.location.relaod).toHaveBeenCalled(); 
expect(windowSpy.close).toHaveBeenCalled(); 

for this last line of code

expect(windowSpy.close).toHaveBeenCalled();

I am getting an error that says

received value must be a mock or spy function. received has value undefined

For

expect(windowSpy.opener.location.relaod).toHaveBeenCalled();

it says:

windowSpy.opener is not defined.

like image 404
Ravi K Avatar asked Dec 10 '25 01:12

Ravi K


2 Answers

You're only mocking window but you're not providing any implementation.

This should help:

windowSpy.mockImplementation(() => ({
  close: jest.fn(),
  opener: {
      location: {
          reload: jest.fn(),
      }
  }
}));
like image 199
Axnyff Avatar answered Dec 11 '25 13:12

Axnyff


If you don't actually need a spy, just a mock, I've had luck with simply reassigning the particular window function:

global.window.opener.location.reload = jest.fn()
like image 43
Andrew Avatar answered Dec 11 '25 14:12

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!