javascript / beginner
Snippet
Verifying Rendered Text Output with React Testing Library
React Testing Library focuses on testing component behavior from a user's perspective. The render method creates the DOM output of a component, and query utilities like screen.getByText inspect the rendered tree to ensure expected text values exist.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
import { render, screen } from '@testing-library/react';import { expect, test } from 'vitest';function Greeting({ name }) {return <h1>Hello, {name}!</h1>;}test('displays the correct greeting text', () => {render(<Greeting name="Alice" />);const headingElement = screen.getByText('Hello, Alice!');expect(headingElement).toBeDefined();});
react
Breakdown
1
render(<Greeting name="Alice" />);
Renders the Greeting component with specified props into a virtual test DOM environment.
2
const headingElement = screen.getByText('Hello, Alice!');
Queries the rendered DOM to locate any visible element containing the exact matching string.
3
expect(headingElement).toBeDefined();
Asserts that the queried heading element exists in the rendered output.