Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    });
});
like image 245
Javier Conde Avatar asked Aug 05 '16 20:08

Javier Conde


People also ask

Is Keydown an event?

The keydown event is fired when a key is pressed. Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

How do you simulate Keydown jest?

To simulate keydown on document with Jest, we create a new KeyboardEvent instance. const event = new KeyboardEvent("keydown", { keyCode: 37 }); document. dispatchEvent(event); to create a new KeyboardEvent instance with the 'keydown' event.


1 Answers

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.

like image 51
David Gilbertson Avatar answered Oct 04 '22 23:10

David Gilbertson