Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 916
ajmajmajma Avatar asked Dec 04 '17 16:12

ajmajmajma


3 Answers

//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' });
  });

...
like image 108
Parth Navadiya Avatar answered Nov 09 '22 19:11

Parth Navadiya


I had the same issue in trying to check if the addEventListener has been called in componentDidMount this seems to work for me (jest, enzyme)

//component
componentDidMount(){
    document.addEventListener("keydown", this.handleKeydownOnSearch, false);
}

....

//in test file ...
it("on component mount we set the keydown listener", () => {
        global.document.addEventListener = jest.fn();
        wrapper = shallow(<ItemSearch />);
        expect(global.document.addEventListener).toHaveBeenCalled();
    });
...
like image 4
stefan Avatar answered Nov 09 '22 17:11

stefan


I mock my document just like you do, and then if I need to use addEventListener() in a test, I just mock it in a beforeEach

  beforeEach(() => {
    document = {
      ...document,
      addEventListener: () => { },
      removeEventListener: () => { }
    }
  })
like image 2
Max Millington Avatar answered Nov 09 '22 19:11

Max Millington