Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
React Interview Essentials
  1. 1.Introduction to React & Basic Setup
  2. 2.JSX, Functional Components & Props
  3. 3.State Management with useState & useEffect
  4. 4.Conditional Rendering & List Management
  5. 5.Event Handling & Form Management
  6. 6.React Router for SPA Navigation
  7. 7.Context API for Global State
  8. 8.Working with Refs & the DOM
  9. 9.Advanced Component Patterns: HOCs & Render Props
  10. 10.Building Reusable Logic with Custom Hooks
  11. 11.Performance Optimization with Memoization
  12. 12.Error Boundaries for Robust UIs
  13. 13.Concurrent React & Suspense
  14. 14.Testing React Components with RTL
  15. 15.Advanced State Management (Overview)
React Interview Essentials
14

React · Lesson 14 of 15 · 4 min

Testing React Components with RTL

This is how you prove you build robust, maintainable UIs and don't just write code that works once.

In an interview, writing a test for a component isn't just about correctness. It's a signal about how you think. A good test demonstrates that you prioritize user experience over implementation details, that your work is resilient to refactoring, and that you build with accessibility in mind. React Testing Library (RTL) is the tool for sending that signal.

How to talk about testing philosophy

The core idea of RTL is: "The more your tests resemble the way your software is used, the more confidence they can give you."

This means you test from the outside in. You find elements the way a user would—by their visible text, their label, or their accessibility role. You interact with them by firing events like clicks and keyboard input. You assert that the visible output changes as expected.

This is a deliberate departure from older libraries like Enzyme, which encouraged testing implementation details. With Enzyme, you could inspect a component's internal state or check what props were passed to a child.

The trap: Tests that inspect internal state are brittle. If you refactor a component from useState to useReducer without changing the user-facing behavior, an implementation-focused test will break. An RTL test will continue to pass, because the user's experience hasn't changed. This is the key trade-off: RTL forces you to give up precise control over internals in exchange for tests that are more durable and meaningful.

In an interview, if asked "Why RTL?", your answer should hit these points:

  1. It tests from the user's perspective, which builds confidence in the actual user experience.
  2. Tests are decoupled from implementation, so they don't break during refactors.
  3. It guides you toward writing more accessible code by prioritizing semantic queries.

Choosing the right query

RTL's query system has a clear, opinionated hierarchy. Following it is non-negotiable and signals you care about accessibility.

The priority order is:

  1. Queries for everyone: getByRole, getByLabelText, getByPlaceholderText, getByText, getByDisplayValue. These are things all users, including those with assistive technologies, use to navigate. getByRole is the top choice.
  2. Semantic queries: getByAltText, getByTitle. These have specific use cases, often for images and tooltips.
  3. The escape hatch: getByTestId. This should be your last resort. Adding data-testid attributes litters your code with test-specific markers that provide no value to the end-user. Use it only when you cannot find an element with any other query.

Each query type comes in three flavors. You need to know which to use when.

  • getBy*: Use this to find an element you expect to be present. It throws an error if the element isn't found, which is what you want for a failing test.
  • queryBy*: Use this to assert an element is not present. It returns null if the element isn't found and doesn't throw. expect(screen.queryByText('Success')).not.toBeInTheDocument().
  • findBy*: Use this to find an element that will appear asynchronously. It returns a promise that resolves when the element is found, and rejects after a timeout. It's a combination of getBy* and waitFor.

This flowchart guides your choice. Internalize it.

Testing asynchronous behavior

Most interesting components have async behavior: fetching data, timers, animations. This is where many candidates stumble. The key is to use findBy* queries or waitFor to handle the time between triggering an action and the UI updating.

Let's test a component that fetches user data.

// src/components/UserFetcher.tsx
import React, { useState, useEffect } from 'react';

interface User { id: number; name: string; email: string; }

const UserFetcher: React.FC = () => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const response = await fetch('https://api.example.com/users/1');
        if (!response.ok) throw new Error('Failed to fetch');
        const data: User = await response.json();
        setUser(data);
      } catch (err: any) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    fetchUser();
  }, []);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!user) return null;

  return (
    <div>
      <h2>{user.name}</h2>
      <p>{user.email}</p>
    </div>
  );
};

export default UserFetcher;

Your test needs to mock the fetch call to be fast and deterministic. Then, you test three states: loading, success, and error.

// src/components/UserFetcher.test.tsx
import React from 'react';
import { render, screen } from '@testing-library/react';
import UserFetcher from './UserFetcher';

// Mock the global fetch API before all tests
beforeAll(() => {
  global.fetch = jest.fn();
});

const mockFetch = global.fetch as jest.Mock;

test('displays loading message initially, then user data', async () => {
  const mockUser = { name: 'John Doe', email: 'john.doe@example.com' };
  mockFetch.mockResolvedValueOnce({
    ok: true,
    json: async () => mockUser,
  });

  render(<UserFetcher />);

  // 1. Assert initial loading state
  expect(screen.getByText('Loading...')).toBeInTheDocument();

  // 2. Wait for the async operation to complete and the UI to update
  const userName = await screen.findByText('John Doe');
  expect(userName).toBeInTheDocument();
  expect(screen.getByText('john.doe@example.com')).toBeInTheDocument();

  // 3. Assert loading state is gone
  expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
});

test('displays an error message on fetch failure', async () => {
  mockFetch.mockResolvedValueOnce({
    ok: false,
  });

  render(<UserFetcher />);

  // Wait for the error message to appear
  const errorMessage = await screen.findByText(/Error: Failed to fetch/i);
  expect(errorMessage).toBeInTheDocument();
  expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
});

This test pattern is a blueprint. You render, assert the initial state, wait for the async update with findBy*, and then assert the final state.

Try it

Write a test for a simple Tooltip component. The component should render a button, and when the user hovers over it, a tooltip div with some text should appear in the document. When the mouse leaves, the tooltip should disappear. Use fireEvent.mouseEnter and fireEvent.mouseLeave. Assert the presence and absence of the tooltip text using getByText and queryByText.

Next: Advanced State Management (Overview) will give you a framework for discussing complex state solutions like Redux, Zustand, and XState.

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Concurrent React & Suspense

Next

Advanced State Management (Overview)