Rendering a Simple Component
What you'll learn: How to write your very first React Testing Library (RTL) test by rendering a component and confirming it exists in the document.
Your First Test in Action
Now that you understand render and screen, it's time to combine them. The simplest possible RTL test renders a component, queries for something the user would see, and asserts it's present.
Here's the pattern:
import { render, screen } from '@testing-library/react';
import { describe, it, expect } from 'vitest';
function Greeting() {
return <h1>Hello, World!</h1>;
}
describe('Greeting', () => {
it('renders the greeting text', () => {
render(<Greeting />);
const heading = screen.getByText('Hello, World!');
expect(heading).toBeInTheDocument();
});
});
Breaking It Down
render(<Greeting />)— RTL creates a virtual DOM and mounts your componentscreen.getByText('Hello, World!')— We query for visible text (what a user would see)expect(heading).toBeInTheDocument()— We assert the element exists in the rendered output
Think of this like asking: "If a user looked at this component, would they see this text?" That's the entire test philosophy in one example.
Why This Matters
You're not checking props, state, or internal logic. You're verifying the user-facing result. If the text appears, the component works — regardless of how it renders that text internally.
Key Takeaway: Your first RTL test renders a component with render(), queries for user-visible content with screen, and asserts it exists with expect().toBeInTheDocument() — focusing entirely on what the user experiences.