javascript / beginner
Snippet
Asserting Rendered Text Content in Component Unit Tests
Unit tests confirm your components render expected text to the screen. React Testing Library provides screen.getByText to query the virtual DOM and verify elements exist in the document.
snippet.js
javascript
1
2
3
4
5
6
7
8
import { render, screen } from '@testing-library/react';import { WelcomeBanner } from './WelcomeBanner';test('renders welcome greeting text', () => {render(<WelcomeBanner username="John" />);const greetingElement = screen.getByText(/welcome, john/i);expect(greetingElement).toBeInTheDocument();});
react
Breakdown
1
render(<WelcomeBanner username="John" />);
Mounts the React component into a virtual testing DOM container.
2
const greetingElement = screen.getByText(/welcome, john/i);
Searches the rendered output for text matching a case-insensitive regular expression.
3
expect(greetingElement).toBeInTheDocument();
Asserts that the queried element is present and attached to the document tree.