Nir Benita
Nir Benita

Reputation: 511

Can't simulate keyDown (jest+enzyme)

Edit: I ended up using onChange to update the value, which has the benefit of mocking entire strings, rather than individual characters.


I'm using keydown to discern whether to update input value, or add a todo.

The functionality works when tested in the browser, but when simulated with enzyme, the todo isn't added to the snapshot (as if the simulation never occurs).

it('should add a new todo', () => {
  const component = mount(<TodoList />)
  const Input = component.find('.new-todo-input')
  let wrapper = toJson(component);
  
  expect(wrapper).toMatchSnapshot()
  
  Input.simulate('keydown', { key: 'z', keyCode: 90, which: 90 })
  Input.simulate('keydown', { key: 'Enter', keyCode: 13, which: 13 })
  
  wrapper = toJson(component);
  
  expect(wrapper).toMatchSnapshot()
})

You can find the rest of the code here.

Upvotes: 1

Views: 5016

Answers (1)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93203

I checked your code in github . Because you are using e.preventDefault(), you should mock it as well :

 Input.simulate('keydown', { preventDefault(){}, key: 'z', keyCode: 90, which: 90 })

Upvotes: 1

Related Questions