Greeting.test.jsx
import render, screen from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import ToggleButton from './ToggleButton'; test('toggles text on click', async () => const user = userEvent.setup(); render(<ToggleButton />);
expect(button).toHaveTextContent(/on/i); ); For API calls or async updates:
npm install --save-dev @testing-library/react @testing-library/jest-dom @testing-library/user-event In your test setup file:
export default function Greeting( name ) return <h1>Hello, name!</h1>;
import render, screen from '@testing-library/react'; import Greeting from './Greeting'; test('displays the correct greeting', () => render(<Greeting name="Alice" />); const heading = screen.getByText(/hello, alice!/i); expect(heading).toBeInTheDocument(); ); Use userEvent (recommended over fireEvent for realistic behavior):
const button = screen.getByRole('button', name: /off/i ); await user.click(button);