const heading = await screen.findByRole('heading', name: /john doe/i ); expect(heading).toBeInTheDocument(); );
If you use Create React App , RTL and Jest are pre-installed. For manual setups (e.g., with Vite/Vitest), you’ll need these core packages:
Greeting.test.jsx
export default Button; // Button.test.js import React from 'react'; import render, fireEvent from '@testing-library/react'; import Button from './Button';
RTL is typically used alongside a test runner like or Vitest . Installation You can install the necessary packages via npm or yarn: testing library/react
| Feature | Testing Library | Enzyme | |---------|----------------|--------| | Query by role/text/label | ✅ First-class | ⚠️ Possible but not encouraged | | Access to component internals (state, props) | ❌ Explicitly avoided | ✅ Easy | | Tests simulate real user behavior | ✅ High | ⚠️ Lower | | Maintenance with refactoring | Low | High (if testing internals) |
npm install --save-dev @testing-library/react jest const heading = await screen
Best Practices for Using React Testing Library | by Frontend Highlights
For API calls or async updates:
To get started with Testing Library/React, you'll need to install the following packages:
npm install --save-dev @testing-library/react @testing-library/jest-dom @testing-library/user-event Use code with caution. const heading = await screen.findByRole('heading'