javascript / beginner
Snippet
Asserting Rendered Content in Component Unit Tests
Component testing checks that a React element correctly displays dynamic props. Using screen.getByRole locates accessible elements, and toHaveTextContent verifies the expected text.
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 Greeting({ name }) {return <h1>Welcome, {name}!</h1>;}test('renders greeting with given prop name', () => {render(<Greeting name="Sarah" />);const heading = screen.getByRole('heading', { level: 1 });expect(heading).toHaveTextContent('Welcome, Sarah!');});
react
Breakdown
1
render(<Greeting name="Sarah" />);
Mounts the React component into a simulated DOM tree for testing.
2
const heading = screen.getByRole('heading', { level: 1 });
Finds the level-1 heading element by its semantic accessibility role.
3
expect(heading).toHaveTextContent('Welcome, Sarah!');
Asserts that the text inside the matched heading matches the expected string.