clarkoy
clarkoy

Reputation: 410

Unable to mock onKeyPress enter on input

I'm trying to mock my Add todo function, it should call the onCreateTodo function when pressed enter and if input is not null

input.component.tsx

if (e.key === "Enter") {
  if (!props.inputRef.current) return;
  props.onCreateTodo(props.inputRef.current.value);
}

<input
    ref={props.inputRef}
    id="todo-input"
    className="ToDo__input"
    placeholder="What needs to be done?"
    onKeyDown={onCreateTodo}
/>

input.test.tsx

const mountedComponent = mount(
  <TodoInput inputRef={inputMock} onCreateTodo={submitMock}
/>

it('Should call the onCreateTodo function when pressed enter', () => {
  expect(submitMock.mock.calls.length).toEqual(0);
  mountedComponent.simulate("change", { target: { value: "foo" } });
  mountedComponent.find('.ToDo__input').prop('onKeyDown')({ key: 'Enter' });
  expect(submitMock.mock.calls.length).toEqual(1);
});

the result is Expected: 1 Received: 0

Upvotes: 0

Views: 121

Answers (1)

Nick Vu
Nick Vu

Reputation: 15520

I think you can try to use simulate

mountedComponent.find('.ToDo__input').simulate('keypress', {key: 'Enter'})

Another problem I can see here that you simulate your value on mountedComponent instead of mountedComponent.find('.ToDo__input')

Potential fix can be

mountedComponent.find('.ToDo__input').simulate("change", { target: { value: "foo" } });

Upvotes: 2

Related Questions