Test window keydown event in Reactjs Test window keydown event in Reactjs reactjs reactjs

Test window keydown event in Reactjs


If you set up your listener like window.addEventListener('keydown', myFunc) then you only need to test myFunc, you don't actually need to test that addEventListener calls your function when a keydown happens.

By always binding events to functions (rather than doing work in a callback) testing is more direct (you're testing your code) and also you can remove event listeners when you're done with them.


I solved it thanks to David's comment just by ignoring the event and setting the state to what I needed for the test. I also found out a different way to test window events in the future. Creating a window class that extends EventEmitter you can receive keydown/keyup events like ctrl through window.emit('keydown',{keyCode: 17}).

This is the code of my_test_helper.js:

import jsdom from 'jsdom';import chai from 'chai';import EventEmitter from 'events';const doc = jsdom.jsdom('<!doctype html><html><body></body></html>');const windowClass = class extends EventEmitter {    constructor() {        super(doc.defaultView);        this.__defineSetter__('onkeydown', f => this.on('keydown', f));        this.__defineSetter__('onkeyup', f => this.on('keyup', f));    }    addEventListener (e,f) {        this.on(e,f);    }};const win = new windowClass();global.document = doc;global.window = win;Object.keys(window).forEach((key) => {  if (!(key in global)) {    global[key] = window[key];  }});