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

Viewed 3395

I have searched online but i didnt 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.

Please someone help !!!

3 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(),
      }
  }
}));

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()

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/

Related