greatTeacherOnizuka
greatTeacherOnizuka

Reputation: 565

Jest test write on textarea input

I am trying to write some mock string to a textarea using Jest and then press Enter but it does not work for whatever reason. My code so far:

test('Should add a message', () => {
  const element = wrapper.find('textarea');
  element.instance().value = 'abc';
  element.simulate('keypress', { key: 'Enter' });

  const newWrapper = wrapper.find('user');
  expect(newWrapper.length).toBe(1);
});

My component:

<textarea
  onKeyUp={sendMessage}
  placeholder='Type your message here and press enter to send...'
  cols='30'
  rows='5'
></textarea>

Just to be clear the textarea is definitely there as the following test passes:

test('Should have a textarea', () => {
  const element = wrapper.find('textarea');
  expect(element.length).toBe(1);
});

Upvotes: 3

Views: 4541

Answers (1)

Barry Michael Doyle
Barry Michael Doyle

Reputation: 10638

In your case, what you are looking for is 'keyUp', not 'keypress'. And instead of key, use keyCode. The keyCode for Enter is 13.

Like this:

element.simulate('keyUp', { keyCode: 13 });

Upvotes: 1

Related Questions