Lesson 3 of 8
React Testing Library - RTL Fundamentals
React Testing Library renders components in a DOM environment and provides queries that reflect how users access content - by role, label, text, and placeholder. The guiding principle: write tests that resemble how a real user would interact with your component.
RTL Queries & Interactions
import { render, screen, within, waitFor, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LoginForm } from './LoginForm';
// ---- Query priority (prefer accessible queries) ----
// By role (best - mirrors what screen readers see)
screen.getByRole('button', { name: /submit/i });
screen.getByRole('textbox', { name: /email/i });
screen.getByRole('checkbox', { name: /agree/i });
// By label text (form inputs)
screen.getByLabelText('Email address');
// By placeholder
screen.getByPlaceholderText('Search...');
// By text content
screen.getByText('Welcome back');
screen.getByText(/hello, .*/i); // regex
// By test ID (last resort - not visible to users)
screen.getByTestId('submit-button');
// ---- Query variants ----
// getBy → throws if not found (default - use for 'expect to exist')
// queryBy → returns null if not found (use for 'expect NOT to exist')
// findBy → async, waits for element (use for async rendering)
screen.getByText('Submit'); // throws if not found
screen.queryByText('Submit'); // returns null
await screen.findByText('Submitted'); // waits up to 1000ms
// Multiple elements
screen.getAllByRole('listitem');
await screen.findAllByRole('option');
// ---- Testing a login form ----
describe('LoginForm', () => {
it('submits with valid credentials', async () => {
const user = userEvent.setup(); // always prefer userEvent over fireEvent
const onSubmit = vi.fn();
render(<LoginForm onSubmit={onSubmit} />);
await user.type(screen.getByLabelText('Email'), 'user@example.com');
await user.type(screen.getByLabelText('Password'), 'secret123');
await user.click(screen.getByRole('button', { name: /sign in/i }));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({
email: 'user@example.com',
password: 'secret123',
});
});
});
it('shows validation error for empty email', async () => {
const user = userEvent.setup();
render(<LoginForm onSubmit={vi.fn()} />);
await user.click(screen.getByRole('button', { name: /sign in/i }));
expect(await screen.findByRole('alert')).toHaveTextContent('Email is required');
// findByRole waits for the alert (async validation) to appear
});
it('disables submit button while loading', async () => {
const user = userEvent.setup();
const slowSubmit = vi.fn(() => new Promise(resolve => setTimeout(resolve, 1000)));
render(<LoginForm onSubmit={slowSubmit} />);
await user.type(screen.getByLabelText('Email'), 'user@example.com');
await user.type(screen.getByLabelText('Password'), 'secret123');
await user.click(screen.getByRole('button', { name: /sign in/i }));
// Button is disabled immediately after click
expect(screen.getByRole('button', { name: /signing in/i })).toBeDisabled();
});
});Testing with Context Providers
// Custom render - wraps with all providers by default
import { render, type RenderOptions } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { MemoryRouter } from 'react-router-dom';
import type { ReactNode } from 'react';
function createTestQueryClient() {
return new QueryClient({
defaultOptions: {
queries: { retry: false, gcTime: 0 }, // no retries in tests
mutations: { retry: false },
},
});
}
interface TestWrapperProps { children: ReactNode; initialPath?: string; }
function TestWrapper({ children, initialPath = '/' }: TestWrapperProps) {
const queryClient = createTestQueryClient();
return (
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[initialPath]}>
{children}
</MemoryRouter>
</QueryClientProvider>
);
}
// Custom render function - use this instead of raw render()
function customRender(
ui: React.ReactElement,
{ initialPath, ...options }: RenderOptions & { initialPath?: string } = {}
) {
return render(ui, {
wrapper: ({ children }) => <TestWrapper initialPath={initialPath}>{children}</TestWrapper>,
...options,
});
}
// Re-export everything from RTL + our custom render
export * from '@testing-library/react';
export { customRender as render }; // override render
// Usage in tests
import { render, screen } from '@/test/utils'; // use custom render
test('renders dashboard', () => {
render(<Dashboard />, { initialPath: '/dashboard' });
expect(screen.getByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
});Common Mistakes - RTL
- Using `fireEvent` instead of `userEvent` - fireEvent triggers raw DOM events; userEvent simulates real user gestures (keyboard, pointer events, focus changes). Always use userEvent
- Testing implementation details - checking internal state, checking component method calls, testing CSS classes. Instead, test behavior: does the error message appear?
- Not waiting for async UI changes - after a user action triggers async work, always use `await screen.findBy...` or `await waitFor(...)`, never `screen.getBy...` for something that appears asynchronously
- Overusing `getByTestId` - test IDs don't reflect how users access content; prefer role, label, text queries. testId is acceptable for helper elements that have no accessible name
- Snapshot tests for complex components - snapshots are extremely fragile and create test maintenance burden with near-zero value for most components; use focused assertions instead
Tip
Tip
Practice React Testing Library RTL Fundamentals in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for React Testing Library - RTL Fundamentals
Practice Task
Note
Practice Task - (1) Write a working example of React Testing Library RTL Fundamentals from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with React Testing Library RTL Fundamentals is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- React Testing Library renders components in a DOM environment and provides queries that reflect how users access content - by role, label, text, and placeholder.
- Using `fireEvent` instead of `userEvent` - fireEvent triggers raw DOM events; userEvent simulates real user gestures (keyboard, pointer events, focus changes). Always use userEvent
- Testing implementation details - checking internal state, checking component method calls, testing CSS classes. Instead, test behavior: does the error message appear?
- Not waiting for async UI changes - after a user action triggers async work, always use `await screen.findBy...` or `await waitFor(...)`, never `screen.getBy...` for something that appears asynchronously
Finished this lesson?