QA
Intermediate LevelReact JS & React 19

Why prefer @testing-library/user-event over fireEvent in React unit tests?

❓ Interview Prompt: Compare `@testing-library/user-event` (simulates full browser user interactions) vs `fireEvent` (dispatches raw synthetic DOM events).

1. 'fireEvent':

Dispatches isolated synthetic DOM events ('fireEvent.click(button)'). Does NOT simulate browser side-effects (e.g. clicking a checkbox does not automatically check it, typing does not trigger focus/blur/keyPress events).

2. 'user-event' (Recommended):

Simulates full realistic browser interaction pipelines ('await userEvent.type(input, 'hello')' triggers 'hover', 'focus', 'keyDown', 'keyPress', 'input', 'keyUp', and 'change' events sequentially!).

Code Implementation Example

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

test('should type username into input field', async () => {
  const user = userEvent.setup(); // 1. Setup user-event instance
  render(<LoginForm />);

  const input = screen.getByLabelText(/username/i);
  await user.type(input, 'alice_dev'); // 2. Simulates full typing sequence!
  expect(input).toHaveValue('alice_dev');
});
💡Simulating full browser user input typing using user-event.
🎯 Interview Key Takeaway

Prefer @testing-library/user-event over fireEvent to test realistic browser interactions including focus, keydown, and input.

#Testing Library#user-event#fireEvent#Testing#Intermediate
Back to all React JS & React 19 Questions→

More React JS & React 19 Interview Questions

Beginner LevelReact JS & React 19

What is JSX and how does it work under the hood?

Beginner LevelReact JS & React 19

What is the difference between props and state in React?

Beginner LevelReact JS & React 19

How does the useState hook work and what is functional updater syntax?