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.
An enter key event can be dispatched like: const event = new KeyboardEvent('keypress', { key: 'enter', }); console. log(event) // KeyboardEvent {isTrusted: false, key: "enter", code: "", location: 0, ctrlKey: false, …} FYI: The react-keydown package is good for implementing keyboard navigation or other shortcuts.
Instead of using a keyCode, I used a key, in the case of 'Enter', using mount
:
wrapper.find('input').simulate('keypress', {key: 'Enter'})
I'm using 'shallow' mount (Enzyme 3.7.0 with Jest 23.6.0). This work for me:
const input = wrapper.find('input');
input.simulate('change', { target: { value: 'abcdefg'} });
input.simulate('keydown', { keyCode: 13 });
Simulate solution is deprecated
Enzyme simulate is supposed to be removed in version 4. Main maintainer is suggesting directly invoking prop functions. One solution is to directly test that invoking those props does the right thing; or you can mock out instance methods, test that the prop functions call them and unit test the instance methods.
You could call key down for example
wrapper.find('input').prop('onKeyDown')({ key: 'Enter' })
or
wrapper.find('input').props().onKeyDown({ key: 'Enter' })
Information about deprecation: https://github.com/airbnb/enzyme/issues/2173
wrapper.find('input').simulate('keydown');
It worked for me...
const wrapper = mount(<App />);
const input = wrapper.find('input');
input.props().onKeyDown({key: 'Enter'});
It actually depends on the implementation. If you've used something like this in your implementation:
if (event.charCode === 13) {
// do something
}
you would simulate the event in your test like this:
wrapper.find('input').simulate('keypress', { charCode: 13 });
Hope it helps :-).
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