Javier Conde Javier Conde - 9 months ago 79
Javascript Question

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

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

Is there a way to test
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) {
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
// Error here
Simulate.keyDown(window, { keyCode: 17 });


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.