How to mock the JavaScript window object using Jest?

danny picture danny · Jan 27, 2017 · Viewed 119.6k times · Source

I need to test a function which opens a new tab in the browser

openStatementsReport(contactIds) {
  window.open(`a_url_${contactIds}`);
}

I would like to mock the window's open function so I can verify the correct URL is passed in to the open function.

Using Jest, I don't know how to mock the window. I tried to set window.open with a mock function but this way doesn't work. Below is the test case

it('correct url is called', () => {
  window.open = jest.fn();
  statementService.openStatementsReport(111);
  expect(window.open).toBeCalled();
});

but it gives me the error

expect(jest.fn())[.not].toBeCalled()

jest.fn() value must be a mock function or spy.
    Received:
      function: [Function anonymous]

What should I do to the test case? Any suggestions or hints are appreciated.

Answer

Andreas Köberle picture Andreas Köberle · Jan 27, 2017

Instead of window use global

it('correct url is called', () => {
  global.open = jest.fn();
  statementService.openStatementsReport(111);
  expect(global.open).toBeCalled();
});

you could also try

const open = jest.fn()
Object.defineProperty(window, 'open', open);