javascript / beginner
Snippet
Testing React Components with Screen Queries
React Testing Library lets you verify that your UI renders expected text without relying on implementation details. The render function mounts the component in a test environment, screen.getByText searches the virtual DOM for matching text, and matchers like toBeInTheDocument confirm the element is present.
snippet.js
javascript
1
2
3
4
5
6
7
8
import { render, screen } from '@testing-library/react';import Greeting from './Greeting';test('renders welcome message text', () => {render(<Greeting name="Alex" />);const headingElement = screen.getByText(/welcome, alex/i);expect(headingElement).toBeInTheDocument();});
react
Breakdown
1
render(<Greeting name="Alex" />);
Mounts the Greeting component into the simulated test DOM with the specified prop.
2
const headingElement = screen.getByText(/welcome, alex/i);
Queries the rendered DOM for an element containing text that matches the case-insensitive regular expression.
3
expect(headingElement).toBeInTheDocument();
Asserts that the queried element exists inside the document body.