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);
});
});
addEventListener
, and the component would still pass the test. – Turbary