Course contentsShow
← React
Lesson 2045 of 2,39646. Testing React with RTLFree lesson

Rendering a Simple Component

Writing your first RTL test: rendering a component and asserting it appears in the document.

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

  1. render(<Greeting />) — RTL creates a virtual DOM and mounts your component
  2. screen.getByText('Hello, World!') — We query for visible text (what a user would see)
  3. 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.