JavaScript and React course ยท Module 13: Testing React

Testing Asynchronous Components - Signals from Deep Space

8 min read ยท
In this lesson5

Many operations in React applications work asynchronously - fetching data from an API, loading resources, delayed updates. It's like receiving signals from deep space - the response doesn't come immediately, you have to wait.

A plain test checks the screen right after render. If the data arrives 50 ms later, the assertion has long since run and the test fails, even though the component works. We need tools that wait for the signal, but not forever.

waitFor - Waiting for the Signal

The waitFor function repeats an assertion check until it succeeds or the timeout expires. The callback you pass may be called many times, so it should contain only assertions:

import { render, screen, waitFor } from '@testing-library/react';

test('loads mission data from API', async () => {
  render(<MissionDetails missionId="apollo-13" />);

  // Spinner is visible immediately
  expect(screen.getByText('Loading...')).toBeInTheDocument();

  // Wait for data
  await waitFor(() => {
    expect(screen.getByText('Apollo 13')).toBeInTheDocument();
  });

  // Spinner should be gone
  expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
});

The order of assertions mirrors the component's life: first the spinner, then the data, and finally the spinner disappears. The last check uses queryByText, because getByText would throw once the element is gone.

waitFor Configuration

You can change the default timings with the second argument:

await waitFor(
  () => {
    expect(screen.getByText('Data loaded')).toBeInTheDocument();
  },
  {
    timeout: 3000,   // Maximum wait time (default 1000ms)
    interval: 100,    // How often to check (default 50ms)
  }
);

Increase timeout only when an operation really takes longer, because long waits slow down the whole test suite.

findBy Queries - Shortcut for waitFor

findBy queries are a shortcut combining waitFor with getBy. They return a Promise that resolves once the element appears:

// These two are equivalent:

// Method 1: waitFor + getBy
await waitFor(() => {
  expect(screen.getByText('Mission loaded')).toBeInTheDocument();
});

// Method 2: findBy (recommended!)
const element = await screen.findByText('Mission loaded');
expect(element).toBeInTheDocument();

Both versions do the same thing, but findBy is shorter and states more clearly what we are waiting for. Keep waitFor for cases where you wait for something other than an element appearing, such as a mock being called.

Example with a Data-Fetching Component

Here is a typical component that fetches a crew list after mounting. It has three states: loading, error and data:

function CrewList({ shipId }) {
  const [crew, setCrew] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch(`/api/ships/${shipId}/crew`)
      .then(res => res.json())
      .then(data => {
        setCrew(data);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, [shipId]);

  if (loading) return <p>Loading crew...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {crew.map(member => (
        <li key={member.id}>{member.name}</li>
      ))}
    </ul>
  );
}

The effect with fetch runs after the first render, so "Loading crew..." always shows first. That transitional state is exactly what we will check.

Testing This Component

In a test we do not want the real network. We replace global.fetch with a jest.fn() mock and decide what it returns:

// Mock fetch
beforeEach(() => {
  global.fetch = jest.fn();
});

test('displays crew members after loading', async () => {
  fetch.mockResolvedValueOnce({
    json: () => Promise.resolve([
      { id: 1, name: 'Captain Nova' },
      { id: 2, name: 'Engineer Bolt' },
    ])
  });

  render(<CrewList shipId="enterprise" />);

  // Loading state
  expect(screen.getByText('Loading crew...')).toBeInTheDocument();

  // Wait for data
  expect(await screen.findByText('Captain Nova')).toBeInTheDocument();
  expect(screen.getByText('Engineer Bolt')).toBeInTheDocument();
  expect(screen.queryByText('Loading crew...')).not.toBeInTheDocument();
});

test('displays error when fetch fails', async () => {
  fetch.mockRejectedValueOnce(new Error('Network error'));

  render(<CrewList shipId="enterprise" />);

  expect(await screen.findByText('Error: Network error')).toBeInTheDocument();
});

mockResolvedValueOnce returns an object that imitates a response with a json method, while mockRejectedValueOnce simulates a network failure. So we cover both paths, success and error, without a single real request.

When every fetch call should get the same response, one line with mockResolvedValue, without Once, is enough:

const data = [{ id: 1, name: 'Captain Nova' }];
global.fetch = jest.fn().mockResolvedValue({ json: () => Promise.resolve(data) });

mockResolvedValue answers the same way on every call, while mockResolvedValueOnce answers only the next one. Choose the Once version when consecutive calls should get different responses, for example an error first and then data.

act() - Synchronization with React

The act() function tells React that we're performing an operation that updates state and requires re-rendering. Let's see it on a launch countdown. The component decreases the counter every second with setInterval:

function CountdownTimer({ seconds }) {
  const [remaining, setRemaining] = useState(seconds);

  useEffect(() => {
    const id = setInterval(() => {
      setRemaining(r => (r > 0 ? r - 1 : 0));
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return <p>{remaining}</p>;
}

Two details matter in tests. The functional update setRemaining(r => ...) always receives the latest value, even though the function inside the interval was created during the first render and on its own would only see the initial remaining. The clearInterval cleanup stops the clock when the component disappears, and RTL unmounts the component after every test, so the interval does not keep ticking in the background of the next test.

Now the test. We import act from the react package, because the old act from react-dom/test-utils is deprecated in React 19:

import { act } from 'react';

test('updates timer display', () => {
  jest.useFakeTimers();
  render(<CountdownTimer seconds={10} />);

  expect(screen.getByText('10')).toBeInTheDocument();

  // Fast-forward time by 3 seconds
  act(() => {
    jest.advanceTimersByTime(3000);
  });

  expect(screen.getByText('7')).toBeInTheDocument();

  jest.useRealTimers();
});

jest.useFakeTimers() replaces the clock, and advanceTimersByTime(3000) moves it forward three seconds without waiting. Advancing the clock changes state outside RTL, which is why we wrap it in act. At the end we restore real timers so we do not disturb other tests.

When is act() Needed?

  • React Testing Library automatically wraps render, fireEvent and userEvent events, and the waiting in waitFor and findBy, in act()
  • You need to use it manually when updating state outside RTL's tools (e.g., fake timers, direct callback calls)

If you see a "not wrapped in act(...)" warning in the console, it signals that some state update happened after the test finished or outside RTL's tools.

Testing Debounced and Throttled Operations

A debounced search box does not send a request after every keystroke; it waits until the user stops typing. Here is such a component. Every new character changes query, and the effect cleanup cancels the previous setTimeout, so onSearch fires only after 300 ms of silence:

function SearchBar({ onSearch, debounceMs = 300 }) {
  const [query, setQuery] = useState('');

  useEffect(() => {
    if (!query) return;
    const id = setTimeout(() => onSearch(query), debounceMs);
    return () => clearTimeout(id);
  }, [query, debounceMs, onSearch]);

  return (
    <input
      aria-label="Search missions"
      value={query}
      onChange={e => setQuery(e.target.value)}
    />
  );
}

The test combines fake timers with userEvent. The advanceTimers option tells the library how to move the replaced clock:

test('calls onSearch once, after the user stops typing', async () => {
  jest.useFakeTimers();
  const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
  const onSearch = jest.fn();

  render(<SearchBar onSearch={onSearch} debounceMs={300} />);

  await user.type(screen.getByRole('textbox'), 'Mars');

  // Before the debounce expires: no request yet
  expect(onSearch).not.toHaveBeenCalled();

  // After the debounce expires
  act(() => {
    jest.advanceTimersByTime(300);
  });

  expect(onSearch).toHaveBeenCalledTimes(1);
  expect(onSearch).toHaveBeenCalledWith('Mars');

  jest.useRealTimers();
});

Without the advanceTimers option, user.type would wait for real delays between keystrokes and the test would hang. After typing, we move time forward by 300 ms, exactly the debounce length. Four keystrokes, yet one call with the full word Mars: that is exactly the promise of debounce that this test checks. Throttling is tested the same way, except you expect at most one call per time window.

waitForElementToBeRemoved

Waiting for an element to disappear (e.g., a spinner). You import the function from @testing-library/react, just like waitFor:

test('hides loading spinner after data loads', async () => {
  render(<DataPanel />);

  // Spinner is visible
  const spinner = screen.getByText('Loading...');

  // Wait for it to disappear
  await waitForElementToBeRemoved(spinner);

  // Data should be visible
  expect(screen.getByText('Data ready')).toBeInTheDocument();
});

The element has to be found before it disappears, which is why getByText comes before waitForElementToBeRemoved. The function waits for the DOM node itself to be removed. If the component only swaps the text inside the same tag, for example the same <p> first shows "Loading..." and then "Data ready", the node stays in place and the test ends with a timeout. In that case wait for the new text with findByText.

My advice: choose findBy when you wait for an element, and waitFor only when you wait for something else. In the next lesson you will learn to mock whole modules and APIs. Remember: an async test is a patient radar that listens for a signal, but with a fixed time limit.

Code for this lesson: App.jsx
import React, { useState, useEffect } from 'react';

// Simulated API: the preview has no server, so the response comes
// from a Promise and setTimeout, just like the mock in the lesson's tests
const MISSIONS = [
  { id: 1, name: 'Apollo 11', status: 'completed' },
  { id: 2, name: 'Artemis I', status: 'active' },
  { id: 3, name: 'Mars 2030', status: 'planned' },
];

const STATUS_LABELS = { completed: 'completed', active: 'active', planned: 'planned' };

function fakeApi(endpoint, delay = 1500) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (endpoint === '/api/missions') {
        resolve(MISSIONS);
      } else {
        reject(new Error('lost contact with mission control'));
      }
    }, delay);
  });
}

// Asynchronous component: loading, then data or an error
function MissionLoader({ endpoint }) {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [attempt, setAttempt] = useState(0);

  useEffect(() => {
    let ignore = false;
    fakeApi(endpoint)
      .then(result => {
        if (!ignore) setData(result);
      })
      .catch(err => {
        if (!ignore) setError(err.message);
      });
    return () => {
      ignore = true;
    };
  }, [endpoint, attempt]);

  if (error) {
    return (
      <div className="error">
        <p role="alert">Signal lost: {error}</p>
        <button
          onClick={() => {
            setError(null);
            setAttempt(a => a + 1);
          }}
        >
          Reconnect
        </button>
      </div>
    );
  }

  if (!data) {
    return (
      <div className="loading" role="status">
        <div className="spinner" />
        <p>Receiving a signal from deep space...</p>
      </div>
    );
  }

  return (
    <div className="mission-data">
      <h3>Missions received ({data.length})</h3>
      <ul>
        {data.map(mission => (
          <li key={mission.id} className={`mission-${mission.status}`}>
            <strong>{mission.name}</strong>
            <span className="status-badge">{STATUS_LABELS[mission.status]}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

// Debounced search: the request goes out only 300 ms after the last keystroke
function DebouncedSearch({ debounceMs = 300 }) {
  const [query, setQuery] = useState('');
  const [sent, setSent] = useState([]);

  useEffect(() => {
    if (!query) return;
    const id = setTimeout(() => {
      setSent(prev => [...prev, query]);
    }, debounceMs);
    return () => clearTimeout(id);
  }, [query, debounceMs]);

  return (
    <div className="search">
      <h3>Debounced search</h3>
      <label htmlFor="mission-search">Search missions</label>
      <input
        id="mission-search"
        value={query}
        onChange={e => setQuery(e.target.value)}
        placeholder="Type fast: Mars"
      />
      <p>Requests sent: {sent.length}</p>
      {sent.length > 0 && <p className="last-query">Last request: {sent[sent.length - 1]}</p>}
    </div>
  );
}

// Countdown: setInterval, a functional update and cleanup with clearInterval
function CountdownTimer({ seconds }) {
  const [remaining, setRemaining] = useState(seconds);
  const [running, setRunning] = useState(false);
  const counting = running && remaining > 0;

  useEffect(() => {
    if (!counting) return;
    const id = setInterval(() => {
      setRemaining(r => Math.max(r - 1, 0));
    }, 1000);
    return () => clearInterval(id);
  }, [counting]);

  return (
    <div className="countdown">
      <h3>Launch countdown</h3>
      <div className="timer-display">
        {remaining > 0 ? (
          <span className="time">{remaining}</span>
        ) : (
          <span className="launched">Liftoff!</span>
        )}
      </div>
      <div className="btn-row">
        <button onClick={() => setRunning(true)} disabled={counting || remaining === 0}>
          {counting ? 'Counting down...' : 'Start countdown'}
        </button>
        <button
          onClick={() => {
            setRunning(false);
            setRemaining(seconds);
          }}
        >
          Reset
        </button>
      </div>
    </div>
  );
}

export default function App() {
  const [endpoint, setEndpoint] = useState('/api/missions');

  return (
    <div className="app">
      <h1>Testing Async - Signals from Space</h1>
      <p className="note">
        The preview shows the working components from the lesson. You run the tests
        with fake timers and findBy in Jest, in your own project.
      </p>

      <div className="controls">
        <button
          onClick={() => setEndpoint('/api/missions')}
          className={endpoint === '/api/missions' ? 'active' : ''}
          aria-pressed={endpoint === '/api/missions'}
        >
          Load missions
        </button>
        <button
          onClick={() => setEndpoint('/api/error')}
          className={endpoint === '/api/error' ? 'active' : ''}
          aria-pressed={endpoint === '/api/error'}
        >
          Simulate error
        </button>
      </div>

      {/* key: when the source changes, the component starts over from the loading state */}
      <MissionLoader key={endpoint} endpoint={endpoint} />
      <DebouncedSearch />
      <CountdownTimer seconds={10} />
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the waitFor function do in React Testing Library?

  2. 2. When do you need to use act() by hand in React tests?

Hands-on tasks in the game

  • Code editor

    Finish the SearchFilter search in the space object atlas. ___BLANK1___: an object matches the search when its name contains the typed text, where neither letter case nor spaces at the start and end of the typed text matter (empty text matches everything). ___BLANK2___: an object matches the category when All is selected (the value 'all') or when its category equals the selected one. ___BLANK3___: when no object is left after filtering, a message with role="status" is shown instead of the list. The test types text into the search field (the searchbox role), picks a category from the list and checks the list items.

  • Horizontal ordering

    Arrange the elements of the fetch mocking syntax using jest.fn() in the correct order:

  • Vertical ordering

    Arrange the stages of testing an asynchronous component in the correct order:

  • Code editor

    Finish CountdownTimer, which counts down the seconds to the rocket launch after you click Start. ___BLANK1___: every second the updater function lowers the current value by 1 (use the current parameter, not the left variable, because the interval is created once and would see an old value). ___BLANK2___: the effect returns a cleanup function that calls clearInterval(id), so that Pause, Reset and unmounting stop the interval. ___BLANK3___: elapsed is the number of seconds that have already passed (seconds minus left); the progress bar shows it in aria-valuenow. The test turns on fake timers and moves time forward second by second.

  1. QuestionwaitFor function in RTL
  2. Questionact() in React tests
  3. Coding taskPractice: Search and Filter
  4. Put in orderFetch mocking syntax
  5. Put in orderStages of testing an async component
  6. Coding taskPractice: Countdown Timer

Useful articles