How do you simulate an keyDown enter event (or others) in Enzyme?

我只是一个虾纸丫 提交于 2020-08-21 04:57:47

问题


I'm trying to simulate a keyDown event, specifically for Enter, keyCode: 13. I've tried a number of different ways of doing this, but none of them are working. I've also looked online and it seems like this feature is either buggy or not working in the current version of Enzyme. Does anyone know definitively if this feature works, and if so, what is the proper syntax for simulating an enter, or other types of key events? Thanks!

This is what I have currently, and it's not working:

const input = wrapper.find('input');
input.simulate('keyDown', {keyCode: 13});

My current Enzyme version is 2.4.1


回答1:


Instead of using a keyCode, I used a key, in the case of 'Enter', using mount:

wrapper.find('input').simulate('keypress', {key: 'Enter'})



回答2:


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 });



回答3:


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




回答4:


wrapper.find('input').simulate('keydown');

It worked for me...




回答5:


const wrapper = mount(<App />);
const input = wrapper.find('input');
input.props().onKeyDown({key: 'Enter'});
  • Enzyme 3.9.0
  • React 16.8.6



回答6:


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 :-).




回答7:


This is working perfectly:

wrapper.find('#id1').simulate('keyDown', {key: 'ArrowRight'});
wrapper.find('#id2').simulate('keyDown', {key: 'Enter'})


来源:https://stackoverflow.com/questions/38960832/how-do-you-simulate-an-keydown-enter-event-or-others-in-enzyme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!