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

后端 未结 8 775
臣服心动
臣服心动 2021-02-02 06:08

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 ar

相关标签:
8条回答
  • 2021-02-02 06:14
    const wrapper = mount(<App />);
    const input = wrapper.find('input');
    input.props().onKeyDown({key: 'Enter'});
    
    • Enzyme 3.9.0
    • React 16.8.6
    0 讨论(0)
  • 2021-02-02 06:18

    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 });
    
    0 讨论(0)
  • 2021-02-02 06:18

    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

    0 讨论(0)
  • 2021-02-02 06:27

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

    wrapper.find('input').simulate('keypress', {key: 'Enter'})
    
    0 讨论(0)
  • 2021-02-02 06:33

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

    0 讨论(0)
  • 2021-02-02 06:35

    If you try to simulate a Event while shallowing an Element you could mock the document.addEventListener method:

    let events = [];
    document.addEventListener = jest.fn((event, cb) => {
        events[event] = cb;
    });
    
    shallow(<YourElement/>);
    
    // trigger the keypress event
    events.keyup({key: 's'});
    
    // your test expectations
    expect(someMethod).toBeCalledTimes(1);
    
    
    0 讨论(0)
提交回复
热议问题