A useful React component test follows the same path a person does: render the component, find a control by its accessible role and name, interact with it, then check the visible result. React Testing Library supplies the rendering and DOM queries; a separate test runner such as Jest or Vitest executes the test.
How the pieces of a React test fit together
React Testing Library (RTL) renders a React tree into a DOM container and provides utilities for querying that DOM. Its guiding principle is that tests should resemble how software is used, so they focus on user-visible behavior rather than component instances or internal implementation details. Testing Library’s introduction explains the library’s purpose and its relationship to test frameworks.
- React Testing Library renders components and helps you inspect the resulting DOM.
user-eventexpresses common user actions such as typing and clicking.- Jest, Vitest, or another compatible runner discovers and runs tests and provides the test environment.
jest-domadds DOM-oriented matchers such astoHaveTextContentandtoBeDisabled.
These are complementary layers, not competing choices. RTL works with different test frameworks; its documentation notes a preference for Jest. Verify setup and compatibility against the versions in your project rather than treating one runner as a requirement of RTL.
Install and configure for your project
Before installing anything, check the project’s package manager, lockfile, React version, and existing test runner. The current RTL introduction shows installation of @testing-library/react with @testing-library/dom; the DOM package is a peer dependency starting with RTL v16. Follow the setup documentation for the versions you actually use rather than copying an unqualified version number from a generic example.
#1 Best Overall
- 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.
You will generally need RTL, user-event, a runner and DOM environment, and—if you want its matchers—jest-dom. Exact configuration differs by runner and project. Consult the runner’s current setup instructions as well as the package documentation; the RTL introduction describes framework support, and the official example demonstrates the matcher import.
The example below uses Jest-style test and expect syntax. It is an illustrative pattern, not a claim that this particular component or test was executed; adapt imports and runner setup to your project.
Write a behavior-focused test
Suppose a form accepts a name and displays a greeting after submission. The component should expose a labeled textbox, a button with an accessible name, and a status message when the greeting is ready.
Rank #2
- 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)
})
- Set up the interaction helper. Create
userEvent.setup()inside the test before rendering, as recommended in the user-event introduction. - Render the component.
rendermounts it into a DOM container available to the test. - Find controls semantically. The textbox is queried by role and its label; the button is queried by role and accessible name.
- Await realistic actions. Typing and clicking are asynchronous user-event interactions, so await each one.
- Wait for the outcome. Because the status may appear after an update,
findByRolewaits for it; the assertion checks the resulting text rather than a component’s internal state.
The exact roles, labels, and output depend on your component. If it does not expose an accessible name or appropriate semantic role, improve the component’s accessible markup instead of weakening the test by default.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Choose queries that reflect the interface
Prefer queries based on what a user or assistive technology can identify. They make a test read like a task and can reveal usability problems such as an unlabeled field.
getByRoleis appropriate when the element should already be present, such as a button before submission.- Use a role together with its accessible name when several controls share a role.
- Use label-based queries for form fields when that is the natural way to identify them.
- Use
findByqueries when an element is expected to appear asynchronously. - Use a test ID only when a meaningful accessible query is impractical. It is a fallback, not a substitute for accessible markup.
These query choices are part of RTL’s user-facing approach; see the query guidance in its introduction and the asynchronous example.
Rank #3
- 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.
Use user-event for ordinary actions
user-event models common interactions as a sequence rather than dispatching only one chosen event. Its helpers account for details such as focus and whether an interaction could normally happen—for example, a browser would not let a user click a hidden or disabled control. The current guide is for user-event@14; follow the installed version’s documentation.
Its helpers are asynchronous. Await actions such as typing, clearing text, selecting an option, and uploading a file. The utility API documentation covers those helpers.
fireEvent remains useful when a test needs to dispatch a particular low-level DOM event that user-event does not implement. For everyday typing and clicking, prefer the higher-level interaction because it better represents the user action being tested. This is a difference in purpose, not a claim that low-level event dispatch is never useful.
Rank #4
- 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
Test asynchronous UI and API-dependent behavior
When an action causes content to appear later, await the interaction and use a findBy query for the expected element. Then assert its meaningful content or state. The official example demonstrates waiting for a heading and checking both its text and a button’s disabled state.
For API-dependent components, mock at the request boundary so the component continues to use its normal request behavior. Testing Library’s example recommends Mock Service Worker (MSW) for modeling API communication, rather than stubbing window.fetch or relying on third-party adapters. Use controlled responses to exercise loading, success, and error UI. This keeps the test about how the component responds to a request while avoiding dependence on a live service.
Share providers with a custom render helper
If components need common context or router providers, a custom render helper can wrap them consistently. RTL’s render accepts a wrapper option for this purpose; see the API documentation. Keep the helper aligned with the providers the application really uses, and retain the same user-facing queries in the tests that call it.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Best Value
- 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.
When act or lower-level React utilities are needed
RTL wraps its APIs with act() in most ordinary cases, so a typical test using render and user-event does not need to add manual act() calls. Reach for direct act guidance only when an advanced case in your actual stack requires it; see RTL’s API documentation.
Do not make deprecated react-dom/test-utils APIs the default for component tests. React’s deprecation warning identifies the change and points to alternatives including RTL’s render.
Common problems and fixes
- “Unable to find an accessible element”: Check the rendered markup and accessible name. Add or correct a label, role, or button text so the element is identifiable to users as well as the test.
- A query finds nothing immediately after a click: If the UI updates asynchronously, use an awaited
findByquery for the element that should appear rather than assuming it is present synchronously. - An interaction helper is not awaited: Await user-event actions; otherwise the assertion may run before the interaction sequence finishes.
- Matcher such as
toHaveTextContentis unavailable: Confirm thatjest-domis installed and imported in the test or shared test setup, and check the setup appropriate to your runner. - The test reaches a live API or is brittle around fetch stubs: Mock the request boundary with MSW and provide the response needed for the loading, success, or error case.
- Manual
act()warnings appear: First check whether the test awaits its interactions and asynchronous UI, and whether it uses RTL APIs that already wrapact(). Do not add manual calls reflexively. - Tests break after an internal refactor despite unchanged behavior: Replace assertions about component instances or internal state with queries and assertions against the rendered DOM.
Or skip the browser setup
ScreenshotNeo is a website screenshot API, not a React test runner or a replacement for the behavior test above. It can capture a rendered page for visual inspection, but it does not verify interactions, accessible queries, or component behavior.
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 API details. Before a capture, it can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.
Free tools Windows power users keep installed
One-click scans. No signup required.
Sign up for ScreenshotNeo’s free plan to try visual captures; use RTL and a test runner for component behavior tests.
Frequently Asked Questions
Does React Testing Library run tests by itself?
No. It renders components and provides DOM queries; Jest, Vitest, or another compatible runner executes the tests.
Should I use getByRole or findByRole?
Use getByRole when the element should already exist. Use findByRole when it is expected to appear asynchronously.
Quick Recap
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.




