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

5.7k views Asked by At

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.

3

There are 3 answers

2
Axnyff On

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(),
      }
  }
}));
0
Andrew On

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()
0
ptmalcolm On

Remarkable Mark provides a solution to this that avoids all the above pitfalls, as well as the reload is not declared configurable error that you may get when you try to modify reload() directly. See:

https://remarkablemark.org/blog/2018/11/17/mock-window-location/

Code is copied here directly from this ^ page:

describe('window.location', () => {
  const { location } = window;

  beforeAll(() => {
    delete window.location;
    window.location = { reload: jest.fn() };
  });

  afterAll(() => {
    window.location = location;
  });

  it('mocks `reload`', () => {
    expect(jest.isMockFunction(window.location.reload)).toBe(true);
  });

  it('calls `reload`', () => {
    window.location.reload();
    expect(window.location.reload).toHaveBeenCalled();
  });
});

Thanks Mark!

https://remarkablemark.org/support/