Home > other >  React testing library user-event keyboard not working
React testing library user-event keyboard not working

Time:11-04

I am using react testing library user-event to test keyboard interactions on my ag grid. I am trying to do the input CTRL , which does something on my grid but isn't working the way I expect it too. It seems like its not registering CTRL , correctly but I am unsure.

below is the userevent keyboard code I did and its not doing that specific input. I copied the same function and had it set to when you click 'p' it does the same thing and that works in the test but CTRL , doesn't. Any thoughts?

I tried a few ways and it's not working.

await user.keyboard('{ctrl},{/ctrl}');

await user.keyboard('{ctrl}{,/}{/ctrl}');

await user.keyboard('{ctrl}[,]{/ctrl}');

CodePudding user response:

The problem is that the comma is not a modifier key, so it can't be used with the ctrl key. The solution is to use the keydown event instead of the keypress event.

Here's an example:

import { fireEvent, render } from '@testing-library/react';

test('can type "p"', () => {
  const { getByTestId } = render(<input data-testid="input" />);
  const input = getByTestId('input');
  fireEvent.keyDown(input, { key: 'p', code: 80, ctrlKey: true });
  expect(input.value).toBe('p');
});
  • Related