React · Lesson 14 of 15 · 4 min
Testing React Components with Jest & React Testing Library
This is how you prove you write production-ready code and can be trusted with a large, evolving codebase.
In an interview, you will be asked how to test a component. Your answer reveals more than just technical knowledge; it shows your philosophy on building maintainable software. The goal isn't 100% coverage. It's writing tests that provide high confidence and don't break on every minor refactor.
This lesson covers the modern approach: using Jest as the test runner and React Testing Library (RTL) to interact with your components from a user's perspective.
Test Behavior, Not Implementation
The single most important principle is to test your components the way a user interacts with them. Don't test internal state, private methods, or specific CSS class names. This creates brittle tests that fail when you refactor, even if the user-facing behavior is unchanged.
This is the core philosophy of React Testing Library. It renders components into a real (though simulated) DOM and gives you tools to find and interact with elements just like a user would. This is a deliberate move away from older libraries like Enzyme that encouraged testing implementation details via shallow rendering and state inspection.
In an interview, say this: "I prefer React Testing Library because it encourages testing from the user's perspective. By querying for elements by their accessible role or visible text, the tests are more resilient to refactoring and provide higher confidence that the application works as intended."
This approach has a powerful side effect: it forces you to build more accessible applications. If you can't easily query for an element by its label or role, it's a sign that your component is not accessible to users relying on screen readers.
Query Elements the Way a User Would
RTL provides queries to find elements: getBy, queryBy, and findBy.
getBy*: Throws an error if the element isn't found. Use it for elements you expect to be present.queryBy*: Returnsnullif the element isn't found. Use it to assert an element is not present.findBy*: Returns a promise. Use it for elements that appear asynchronously.
The key is how you query. RTL has a recommended priority that mirrors how users perceive your UI. Following this hierarchy makes your tests more robust.
The trap: Overusing getByTestId. While it seems convenient, it adds test-specific attributes to your production code and tests an implementation detail. Use it only as a last resort for elements that have no other accessible handle, like a dynamically generated background div.
Test an Asynchronous Form
The most common real-world components involve user input and asynchronous actions. This example covers validation, loading states, and API calls. It's a perfect scenario to demonstrate your testing skills.
Here's a form that takes a username and calls an onSubmit prop, which we'll assume is an API call.
// src/UserForm.tsx
import React, { useState } from 'react';
interface UserFormProps {
onSubmit: (username: string) => Promise<string>;
}
const UserForm: React.FC<UserFormProps> = ({ onSubmit }) => {
const [username, setUsername] = useState('');
const [message, setMessage] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setMessage('');
if (username.trim() === '') {
setError('Username cannot be empty.');
return;
}
setLoading(true);
try {
const response = await onSubmit(username);
setMessage(response);
} catch (err: any) {
setError(err.message || 'Submission failed.');
} finally {
setLoading(false);
}
};
return (
<form onSubmit={handleSubmit}>
<h2>User Registration</h2>
<div>
<label htmlFor="username-input">Username:</label>
<input
id="username-input"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
disabled={loading}
/>
</div>
<button type="submit" disabled={loading}>
{loading ? 'Submitting...' : 'Register'}
</button>
{message && <p role="status">{message}</p>}
{error && <p role="alert">{error}</p>}
</form>
);
};
export default UserForm;
Now, let's test it. Notice the use of userEvent over fireEvent—it more closely simulates a user's full sequence of browser events. Also, note the use of jest.fn() to mock the API call and async/await with findBy* to handle the asynchronous UI updates.
// src/UserForm.test.tsx
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import UserForm from './UserForm';
describe('UserForm', () => {
const mockOnSubmit = jest.fn();
beforeEach(() => {
mockOnSubmit.mockClear();
});
test('submits with valid data and displays success', async () => {
mockOnSubmit.mockResolvedValueOnce('User registered!');
render(<UserForm onSubmit={mockOnSubmit} />);
const usernameInput = screen.getByLabelText(/username/i);
const submitButton = screen.getByRole('button', { name: /register/i });
await userEvent.type(usernameInput, 'testuser');
await userEvent.click(submitButton);
expect(submitButton).toBeDisabled();
expect(screen.getByRole('button', { name: /submitting/i })).toBeInTheDocument();
expect(mockOnSubmit).toHaveBeenCalledWith('testuser');
expect(await screen.findByRole('status')).toHaveTextContent('User registered!');
});
test('displays an error message on submission failure', async () => {
mockOnSubmit.mockRejectedValueOnce(new Error('Network error'));
render(<UserForm onSubmit={mockOnSubmit} />);
await userEvent.type(screen.getByLabelText(/username/i), 'failuser');
await userEvent.click(screen.getByRole('button', { name: /register/i }));
expect(await screen.findByRole('alert')).toHaveTextContent('Network error');
});
test('shows a validation error if username is empty', async () => {
render(<UserForm onSubmit={mockOnSubmit} />);
await userEvent.click(screen.getByRole('button', { name: /register/i }));
expect(screen.getByRole('alert')).toHaveTextContent('Username cannot be empty.');
expect(mockOnSubmit).not.toHaveBeenCalled();
});
});
Avoid Common Testing Traps
A few common mistakes immediately signal a lack of experience.
Trap 1: Not waiting for async updates. If your test interacts with something that causes an async state change (like a data fetch), your assertions will run before the UI updates. This causes flaky tests. Always use async/await with findBy* queries or wrap state updates in waitFor.
Trap 2: Testing components that use context without a provider. If a component consumes a context (useContext(MyContext)), rendering it alone will cause a crash. You must wrap it in the corresponding provider during the test. You can even create a custom render utility to do this automatically for all tests.
Trap 3: Ignoring act() warnings. RTL's render and userEvent methods are wrapped in act() for you. If you see a warning about act(), it means a state update was triggered outside of these managed functions. This is a sign your test is not correctly waiting for updates to finish before making assertions. Find the source of the update and wrap it properly.
Try it
Take a component from one of your own projects that fetches data. Write three tests for it: one for the loading state, one for the success state, and one for the error state. Use jest.fn() to mock the fetch call and control its outcome for each test case. This will take about 20 minutes.
Next: We'll cover "Advanced React Features & Modern Concepts" to round out your knowledge of the modern React ecosystem.
Lock it in — apply this lesson under interview conditions.