Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a behavior-focused React test, render the component, find controls by accessible role and name or by label, perform the interaction with user-event, and assert what appears in the DOM. React Testing Library supplies the render and query tools; a separate test runner such as Jest or Vitest discovers and runs the test.

How the React testing pieces fit together

Testing Library’s guiding principle is: “The more your tests resemble the way your software is used, the more confidence they can give you.” Its React library renders a component tree into a DOM container and provides utilities for querying that rendered DOM. It is not a test runner. Testing Library’s React Testing Library introduction explains the approach.

  • React Testing Library: renders React and helps locate DOM elements.
  • user-event: expresses typical user actions, such as typing and clicking.
  • Jest, Vitest, or another compatible runner: discovers and executes tests and supplies the project’s test environment.
  • jest-dom: adds DOM-oriented assertions such as toHaveTextContent and toBeDisabled.

Choose and configure the runner separately from React Testing Library. Testing Library documents a preference for Jest, while its example also mentions Vitest support for the jest-dom matcher package. Check the setup instructions for the versions already in your project rather than assuming one runner or package configuration fits every React app. React Testing Library introduction · React Testing Library example

Install and configure the test dependencies

Installation depends on the app’s package manager, React version, runner, and lockfile. The current Testing Library introduction shows installing @testing-library/react with @testing-library/dom; the DOM package is a peer dependency starting with React Testing Library v16. Check the project’s actual versions and the official setup documentation before changing dependencies. React Testing Library introduction

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Add the runner and DOM matcher package using the instructions for the runner selected by the project. Ensure the runner uses a DOM environment for component tests, and load the appropriate jest-dom setup for that runner. The example below assumes a configured environment in which test, expect, and the jest-dom matchers are available; adapt imports and setup to the project.

Write a small behavior-focused test

Suppose GreetingForm has a textbox labeled “Name,” a “Submit” button, and displays an asynchronous greeting in an element with the status role. The following is an illustrative pattern; the component and accessible names must match your real UI.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import '@testing-library/jest-dom'
import GreetingForm from './GreetingForm'

test('shows a greeting after submission', async () => {
  const user = userEvent.setup()
  render(<GreetingForm />)

  await user.type(screen.getByRole('textbox', { name: /name/i }), 'Ada')
  await user.click(screen.getByRole('button', { name: /submit/i }))

  expect(await screen.findByRole('status')).toHaveTextContent(/hello, ada/i)
})
  1. Set up the interaction helper. Create userEvent.setup() inside the test before rendering.
  2. Render the component. render mounts it into the test DOM.
  3. Find the controls as a user would. The textbox is located by role and accessible name; the button is located by role and name.
  4. Perform the interaction. Await typing and clicking because user-event helpers are asynchronous.
  5. Wait for the result. findByRole waits for the status element to appear; then the assertion checks its user-visible text.

Testing Library’s example uses the same core pattern: render, interact, wait for an element, and assert its content or state. React Testing Library example

Choose queries that describe the interface

Prefer queries based on semantics that matter to users and assistive technology. They make tests resemble tasks and can reveal missing accessible names or roles.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
  • getByRole is appropriate when the element should already exist. Include its accessible name when there may be more than one matching role.
  • Use a label query or a role-and-name query to find form fields. A labeled textbox is generally easier to understand and use than an unlabeled one.
  • findBy queries are for elements expected to appear asynchronously; they wait for the matching element.
  • Use a test ID only when a meaningful user-facing query is impractical. It is a fallback, not the default way to locate controls.

These query and rendering principles are described in the React Testing Library introduction and the React Testing Library API.

Use user-event for normal interactions

user-event models a fuller interaction sequence than dispatching one event with fireEvent. It accounts for behaviors such as focus and rejects actions a browser would prevent on hidden or disabled controls. The current user-event guide documents v14; use the documentation corresponding to the version installed in your project. Introduction to user-event

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Its helpers are asynchronous, so await them. The utility API includes operations for clearing text, selecting options, typing, and uploading files. Use fireEvent when a test specifically needs to dispatch a low-level DOM event that user-event does not implement; do not use it as the default for ordinary clicks or typing. user-event Utility APIs

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Test asynchronous UI and API responses

Wait for the visible state

When an update completes later, wait for the element that represents the expected outcome with an async query such as findByRole, then assert meaningful text or state. For example, an API-backed component test can verify a loading state, wait for a result heading, check its content, and confirm that a load button becomes disabled if that is the intended behavior. React Testing Library example

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Mock at the request boundary

For API-dependent UI, the official example recommends Mock Service Worker (MSW) to model network communication declaratively, rather than stubbing window.fetch or relying on third-party adapters. Keep the component using its ordinary request path, and vary the mocked response to cover the loading, success, and error states your UI supports. React Testing Library example

Reuse provider setup without testing internals

If components need shared context or a router, create a custom render helper that wraps them with those providers. React Testing Library’s render API accepts a wrapper option for this purpose. Keep the test focused on observable behavior rather than component instances or implementation details; that makes it less likely that a refactor breaks a test without changing what a user experiences. React Testing Library API

React’s react-dom/test-utils APIs are deprecated; React’s guidance points to alternatives including React Testing Library’s render. Testing Library also says its APIs wrap act() in most cases, so ordinary tests generally do not need direct manual act() calls. Reserve manual act() for an advanced case when the chosen stack requires it. React: react-dom/test-utils Deprecation Warnings · React Testing Library API

Troubleshoot common test failures

  • “Unable to find role” or “Unable to find label”: Check that the element is rendered in the current state and that its role, label, and accessible name match the query. If the result appears after asynchronous work, use an appropriate findBy query.
  • Interaction is not awaited: Await user-event actions such as type and click; otherwise the assertion may run before the interaction finishes.
  • Matchers such as toHaveTextContent are unavailable: Confirm that jest-dom is installed and loaded in the test setup for the runner in use.
  • Provider-dependent UI fails to render: Render through a helper that supplies the required context, router, or other wrapper.
  • API results vary or tests depend on a live service: Mock the request at the network boundary with MSW and provide deliberate responses for each state.
  • Test setup conflicts with installed package versions: Verify React Testing Library, its DOM peer dependency, user-event, the runner, and matcher setup against the project lockfile and current setup guidance.

Or skip the browser setup

If what you need is a screenshot of a page rather than a React component behavior test, ScreenshotNeo is a website screenshot API and MCP server. A single GET request can return a PNG, JPEG, WebP, or PDF. For example, with cURL:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for options and response details. Cookie banners, newsletter popups, and chat widgets are removed before capture; bot checks, blank pages, and failed loads are not billed. Its MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up free for ScreenshotNeo.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.