Samm
Samm

Reputation: 105

How to simulate/test key press using Jest?

I'm trying to simulate/test the keypress event which calls props.onClick. I successfully simulated the onClick with similar testing code, but the keypress doesn't work.

When I tested it manually by pressing the Enter key, it works as it should, but when I try to write tests for it, it keeps failing and I'm not sure why. I put a logger in the useEffect function, and it gets called during the test, but it fails and gives an error that onClickFnc was never called.

In my button function component, I bind an event listener:

button.js

  useEffect(() => {
    if (enterEnable) {
      window.addEventListener('keydown', onEnterPress);
      return () => window.removeEventListener('keydown', onEnterPress);
    }
  });

  const onEnterPress = e => {
    if (e.which == 13) {
      onClickSync(e);
    }
  };

  const onClickSync = e => {
    props.onClick(e);
  };

button.test.js

  it('check ButtonLoader enable enter to work', () => {

    const onClickFnc = jest.fn(); 
    const wrapper = shallow(<ButtonLoader {...props} enterEnable={true} onClick={onClickFnc}/>);
    wrapper.find('button').simulate('keypress', {key: 'Enter'})
    expect(onClickFnc).toBeCalled();
  });

Error:

    expect(jest.fn()).toBeCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

How can I successfully test this?

Upvotes: 2

Views: 8965

Answers (2)

Jitendra Soni
Jitendra Soni

Reputation: 1

try with this code

    element.simulate('keydown', { key: 'Enter' });

this worked fine for me. hope it also works for you.

Upvotes: 0

user2908484
user2908484

Reputation: 23

Try this instead

wrapper.find('button').simulate('keydown', {which: 13})

From what I have seen, simulate doesn't create an event object from the arguments. Instead it passes the object as is.

Upvotes: 1

Related Questions