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);
});
});
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With