Testing User Interactions (userEvent)

There isn't much point in testing a frontend application or React component if we can't trigger user interaction such as clicking on elements or typing things!

The recommended way to do things like this is with userEvent, from the @testing-library/user-event package.

The userEvent functions simulate user interactions as realistically as possible.

For example, clicking a button triggers a sequence of related events (e.g., pointerover/mouseover, mousedown, focus, mouseup, click). Using userEvent.click() simulates that, in the same sequence a real browser would.

import {
  render,
  screen,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';

test('userEvent click example', async () => {
  const user = userEvent.setup();

  render(<MyComponent />);
  const button =
    screen.getByRole('button');

  await user.click(button);
});

Note: There's also fireEvent from React Testing Library which is simpler but less realistic. If possible, you should aim to trigger events via userEvent for more accurate testing.

Loading full lesson content & code...

Ready to try running tests for this lesson?