React + enzyme unit tests, can't access window.addEventListener

ajmajmajma picture ajmajmajma · Dec 4, 2017 · Viewed 10.4k times · Source

I have some unit tests set up, testing with enzyme's shallow method with a jsdom configuration. This has been working well until I have run into a component where I am using window.addEventListener. The unit tests is now giving back the error of

TypeError: window.addEventListener is not a function

I have my test helpers set up for JSdom like so

import jsdom from 'jsdom';

...

global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = document.defaultView;
global.navigator = {userAgent: 'node.js'};

this was working fine, then I upgraded to enzyme 3.x, and now I am getting this error.

I am wondering do i need to manually mock the addEventListener now, or is there something I am doing wrong to access this.

Answer

Parth Navadiya picture Parth Navadiya · Oct 25, 2018
//in test file ...

    it("should render KeyStrokeHandler", () => {
    // Set-up event listener mock
    const map = {};
    window.addEventListener = jest.fn((event, callback) => {
      map[event] = callback;
    });

    // Mount component that has set callback for keydown event
    const wrapper = mount(<KeyStrokeHandler />);

    // Trigger keydown event
    map.keydown({ key: 'Enter' });
  });

...