Testing interaction - userEvent vs fireEvent

When testing your React applications, you will almost definitely need to simulate some user interactions.

In this lesson we will cover how to trigger simulations of users clicking on things, typing in text boxes, submitting forms and more.

There are two main ways to fire events using React Testing Library - fireEvent and userEvent.

Continue to read this introduction lesson (which explains the main differences between fireEvent and userEvent, and when to use each one), and we will dive into more detail into both of them in the subsequent lessons!

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

function LoginForm() {
  return (
    <form>
      <input
        type="text"
        placeholder="Username"
      />
      <button>Login</button>
    </form>
  );
}

test('user interaction with fireEvent', () => {
  render(<LoginForm />);

  fireEvent.click(
    screen.getByRole('button')
  );

  fireEvent.change(
    screen.getByRole('textbox'),
    {
      target: {
        value: 'Hello from fireEvent',
      },
    }
  );
});

test('user interaction with userEvent', async () => {
  render(<LoginForm />);
  await userEvent.click(
    screen.getByRole('button')
  );

  await userEvent.type(
    screen.getByRole('textbox'),
    'Hello from userEvent'
  );
});

Loading full lesson content & code...

Ready to try running tests for this lesson?