4 Hours

5. React Testing Library: Component Testing

React

React Testing Library (RTL) is the industry standard for testing React components. It encourages testing components as users would interact with them — by finding elements by text, role, and label, not by implementation details like component instances or state.

The key insight is that tests should focus on behavior, not implementation. RTL's philosophy is "the more your tests resemble the way your software is used, the more confidence they can give you." This means testing what the user sees and does, not testing internal state or implementation details. Understanding RTL is essential for React testing.

This module covers rendering components, finding elements, user interactions, and testing async behavior.

Rendering and Finding Elements

RTL's render function renders a React component in a test environment. You then use queries to find elements in the rendered output. RTL provides several query types: getBy (throws if not found), findBy (async, waits for element), queryBy (returns null if not found), and getAllBy (returns array).

Queries are prioritized by what they find: getByRole (best for accessibility), getByLabelText (best for forms), getByPlaceholderText, getByText, and getByTestId (last resort). Using proper queries makes your tests more resilient and accessible.

User Interactions with fireEvent and userEvent

fireEvent is RTL's basic event simulation. It triggers DOM events like click, change, and submit. userEvent is a more advanced library that simulates real user interactions (click, type, tab, etc.). userEvent is preferred because it more closely mimics actual user behavior, including focus/blur events and keyboard interactions.

For most tests, use userEvent. It's more realistic and catches more issues. Use fireEvent only when you need to test specific DOM events directly.

React (JSX)
// Counter component
function Counter({ initialCount = 0 }) {
  const [count, setCount] = useState(initialCount);
  
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
); } // Counter test import { render, screen } from @testing-library/react; import userEvent from @testing-library/user-event; import { Counter } from ./Counter; test(renders initial count, () => { render(); // Find by text const heading = screen.getByText(Count: 5); expect(heading).toBeInTheDocument(); }); test(increments count when button clicked, async () => { const user = userEvent.setup(); render(); const incrementButton = screen.getByRole(button, { name: /increment/i }); const heading = screen.getByText(Count: 0); await user.click(incrementButton); expect(heading).toHaveTextContent(Count: 1); }); // Form component with userEvent test(submits form with user input, async () => { const handleSubmit = jest.fn(); render(); const user = userEvent.setup(); // Fill form fields const emailInput = screen.getByLabelText(/email/i); const passwordInput = screen.getByLabelText(/password/i); const submitButton = screen.getByRole(button, { name: /submit/i }); await user.type(emailInput, test@example.com); await user.type(passwordInput, password123); await user.click(submitButton); expect(handleSubmit).toHaveBeenCalledWith({ email: test@example.com, password: password123 }); });

Testing Async Components

Async components that fetch data or use timers require special handling. RTL provides findBy queries that wait for elements to appear. You can also use waitFor for more complex waiting scenarios. These tools make async testing straightforward.

React (JSX)
// Async component
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    fetchUser(userId).then(user => {
      setUser(user);
      setLoading(false);
    });
  }, [userId]);
  
  if (loading) return <div>Loading...
; return
Name: {user.name}
; } // Async test import { render, screen, waitFor } from @testing-library/react; jest.mock(./api); test(displays user data after fetch, async () => { const mockUser = { id: 1, name: Alice }; fetchUser.mockResolvedValue(mockUser); render(); // Initially shows loading expect(screen.getByText(Loading...)).toBeInTheDocument(); // Wait for user data to appear const nameElement = await screen.findByText(Name: Alice); expect(nameElement).toBeInTheDocument(); });

Try It Yourself: Testing a React Component

Follow these steps to practice testing React components with RTL.

Step 1: Set up the project
npx create-react-app react-testing-demo<br>cd react-testing-demo<br>npm install --save-dev @testing-library/react @testing-library/user-event @testing-library/jest-dom

Step 2: Create a component
Create src/TodoList.js:
import { useState } from <strong><code>react;

function TodoList() {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState('');

const addTodo = () => {
if (input.trim()) {
setTodos([...todos, input]);
setInput('');
}
};

const removeTodo = (index) => {
setTodos(todos.filter((_, i) => i !== index));
};

return (


Todo List



value={input}
onChange={(e) => setInput(e.target.value)}
placeholder=Add todo
/>



    {todos.map((todo, index) => (

  • {todo}


  • ))}

Total: {todos.length}


);
}

export default TodoList;

Step 3: Write the tests
Create src/TodoList.test.js:
import { render, screen } from <strong><code>@testing-library/react;
import userEvent from @testing-library/user-event;
import TodoList from ./TodoList;

describe(TodoList, () => {
test(renders empty list initially, () => {
render();
expect(screen.getByText(Todo List)).toBeInTheDocument();
expect(screen.getByText(Total: 0)).toBeInTheDocument();
expect(screen.queryAllByRole(listitem)).toHaveLength(0);
});

test(adds a todo when Add button clicked, async () => {
const user = userEvent.setup();
render();

const input = screen.getByPlaceholderText(Add todo);
const addButton = screen.getByText(Add);

await user.type(input, Buy milk);
await user.click(addButton);

expect(screen.getByText(Buy milk)).toBeInTheDocument();
expect(screen.getByText(Total: 1)).toBeInTheDocument();
});

test('removes a todo when Delete button clicked', async () => {
const user = userEvent.setup();
render();

const input = screen.getByPlaceholderText(Add todo);
const addButton = screen.getByText(Add);

await user.type(input, Buy milk);
await user.click(addButton);
await user.type(input, Buy eggs);
await user.click(addButton);

const deleteButtons = screen.getAllByText(Delete);
await user.click(deleteButtons[0]);

expect(screen.queryByText(Buy milk)).not.toBeInTheDocument();
expect(screen.getByText(Buy eggs)).toBeInTheDocument();
expect(screen.getByText(Total: 1)).toBeInTheDocument();
});

test(does not add empty todo, async () => {
const user = userEvent.setup();
render();

const addButton = screen.getByText(Add);
await user.click(addButton);

expect(screen.getByText(Total: 0)).toBeInTheDocument();
});
});

Step 4: Run the tests
npm test

Try It Yourself: Add a feature to mark todos as completed. Write tests for the new feature.

Knowledge Check

Ready to test your understanding of 5. React Testing Library: Component Testing?

Back