Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
});
like image 370
greatTeacherOnizuka Avatar asked Aug 11 '26 23:08

greatTeacherOnizuka


1 Answers

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 });
like image 90
Barry Michael Doyle Avatar answered Aug 13 '26 14:08

Barry Michael Doyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!