Course contentsShow
← React
Lesson 2072 of 2,39646. Testing React with RTLFree lesson

Testing Focus Behavior with user-event

How user-event properly triggers focus and blur events when clicking or tabbing between elements.

Testing Focus Behavior with user-event

You'll learn how user-event properly simulates focus and blur events when users click or tab between elements, unlike lower-level alternatives.

Why Focus Behavior Matters

When users interact with forms, modals, or complex UIs, focus management is critical for accessibility and UX. Real users trigger focus changes by clicking elements or tabbing through them. Your tests should verify this behavior works correctly—including visible focus indicators, screen reader announcements, and event handlers.

How user-event Handles Focus

user-event simulates the complete event sequence a browser fires during real interactions:

  • Clicking an element: triggers mousedown, focus (if focusable), mouseup, click—and blur on the previously focused element
  • Tabbing: triggers keydown, keyup, focus on the next element, and blur on the previous one

This means focus-related side effects (like conditional rendering or validation) fire naturally in your tests.

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

test('input shows focus indicator when tabbed', async () => {
  const user = userEvent.setup();
  
  render(
    <div>
      <input aria-label="First name" />
      <input aria-label="Last name" />
    </div>
  );

  const firstInput = screen.getByLabelText('First name');
  const lastInput = screen.getByLabelText('Last name');

  await user.click(firstInput);
  expect(firstInput).toHaveFocus();

  await user.tab();
  expect(lastInput).toHaveFocus();
  expect(firstInput).not.toHaveFocus();
});

Unlike fireEvent.focus(), which directly fires only the focus event, user-event respects the browser's natural focus flow—including blur, focus order, and intermediate events.

Key Takeaway: user-event accurately simulates focus/blur events in the order users experience them, making your tests reliable for accessibility features and focus-dependent logic.