javascript / beginner
Snippet
Asserting Rendered Heading Text Using React Testing Library
Unit testing in React validates that components mount and output expected DOM content correctly using accessible query methods like getByRole.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
import { render, screen } from '@testing-library/react';import '@testing-library/jest-dom';function WelcomeBanner() {return <h1>Welcome to the Platform</h1>;}test('renders platform heading correctly', () => {render(<WelcomeBanner />);const headingElement = screen.getByRole('heading', { level: 1 });expect(headingElement).toHaveTextContent('Welcome to the Platform');});
react
Breakdown
1
render(<WelcomeBanner />);
Mounts the React component into a virtual testing DOM container.
2
const headingElement = screen.getByRole('heading', { level: 1 });
Queries the document for an h1 element using accessibility roles.
3
expect(headingElement).toHaveTextContent('Welcome to the Platform');
Asserts that the queried element contains the expected text string.