Search code examples
javascriptreactjsreactjs-testutils

Test window keydown event in Reactjs


The component I am writing needs to change its behaviour depending on whether ctrl is pressed or not.

I use a window.onkeydown event but Simulate from React Test Utils doesn't allow me to dispatch events against window. I've also tried window.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 17 })); but mocha/node does not recognize KeyboardEvent.

Is there a way to test window.onkeydown using React Test Utils? if not, is there a better way to do it in mocha for node?

Here is some code to ilustrate the issue:

describe('On Keydown', () => {
    it('fires the event', () => {
        // Component
        const Component = class extends React.Component {
            constructor(props) {
                super(props);
                this.state = { key: false };
                window.addEventListener('keydown', e => this.setState({ key: true }));
                window.addEventListener('keyup', e => this.setState({ key: false }));
            }
            render() {
                return <span>test</span>
            };
        };
        // Rendering
        const rendered = renderIntoDocument(<Component/>);
        // Firing event
        expect(rendered.state.key).to.equal(false);
        // Error here
        Simulate.keyDown(window, { keyCode: 17 });
        expect(rendered.state.key).to.equal(true);
    });
});

Solution

  • 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.