How to Test Components That Use Context :👈 👉:How to Write Integration Tests for React Pages

How to Test Components with Asynchronous Data

How to Test Components with Asynchronous Data in React

1. What Is Asynchronous Data in React?

Asynchronous data is information that takes time to retrieve or process. React applications commonly fetch data from APIs using fetch(), Axios, or other services.

For example, when a component fetches a list of users from an API, the request does not complete immediately.

During this process, the component may display different states:

  • Loading: Data is being fetched.
  • Success: Data has been received successfully.
  • Error: The API request has failed.
  • Empty: The API returned no records.

We should test all these states to ensure that the component behaves correctly.

2. Tools Required for Testing

The following tools are commonly used for asynchronous React component testing.

Tool Purpose
React Testing Library Renders components and checks user-visible behavior.
Vitest Runs tests and provides mocking functions.
user-event Simulates user interactions.
jest-dom Provides additional DOM assertions.
MSW Mocks API requests at the network level.

3. Example Component That Fetches API Data

Let's create a component that fetches a list of users from an API.

UserList.jsx

import { useEffect, useState } from "react";
function UserList() {
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");
    async function fetchUsers() {
        try {
            setLoading(true);
            setError("");
            const response = await fetch("/api/users");
            if (!response.ok) {
                throw new Error("Failed to fetch users");
            }
            const data = await response.json();
            setUsers(data);
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    }
    useEffect(() => {
        fetchUsers();
    }, []);
    if (loading) {
        return <p role="status">Loading users...</p>;
    }
    if (error) {
        return (
            <div>
                <p role="alert">{error}</p>
                <button onClick={fetchUsers}>
                    Retry
                </button>
            </div>
        );
    }
    if (users.length === 0) {
        return <p>No users found</p>;
    }
    return (
        <ul>
            {users.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}
export default UserList;

This component supports loading, success, error, empty and retry states.

4. Understanding Asynchronous Testing Methods

React Testing Library provides three important asynchronous query methods.

1. findBy...

Use findBy when an element is expected to appear asynchronously.

expect(
    await screen.findByText("John")
).toBeInTheDocument();

It waits for the element to appear and returns a Promise.

2. waitFor()

Use waitFor() when you need to wait for an assertion or condition to become true.

await waitFor(() => {
    expect(mockFunction).toHaveBeenCalled();
});

It repeatedly executes the callback until the assertion passes or the timeout is reached.

3. queryBy...

Use queryBy when checking whether an element is absent.

expect(
    screen.queryByText("Loading users...")
).not.toBeInTheDocument();

Important: Do not use findBy merely to check that an element is absent. Use queryBy for that purpose.

5. Test Loading State

We need to verify that the loading message appears while the API request is still pending.

We can use a manually controlled Promise to keep the request pending.

UserList.test.jsx

import { render, screen } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import UserList from "./UserList";
it("should display loading message while fetching users", () => {
    vi.stubGlobal(
        "fetch",
        vi.fn(() => new Promise(() => {}))
    );
    render(<UserList />);
    expect(
        screen.getByRole("status")
    ).toHaveTextContent("Loading users...");
});

Explanation:

  1. Mock fetch() with a Promise that never resolves during this test.
  2. Render UserList.
  3. The API request remains pending.
  4. Verify that the loading message is displayed.

6. Test Successful API Response

Now test whether the component displays the users returned by the API.

import { render, screen } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import UserList from "./UserList";
it("should display users after successful API response", async () => {
    vi.stubGlobal(
        "fetch",
        vi.fn().mockResolvedValue({
            ok: true,
            json: async () => [
                { id: 1, name: "John" },
                { id: 2, name: "David" }
            ]
        })
    );
    render(<UserList />);
    expect(
        await screen.findByText("John")
    ).toBeInTheDocument();
    expect(
        screen.getByText("David")
    ).toBeInTheDocument();
    expect(
        screen.queryByText("Loading users...")
    ).not.toBeInTheDocument();
});

What does this test verify?

  • The API request succeeds.
  • The returned users are displayed.
  • The loading message disappears.

7. Test API Error Response

We should verify how the component behaves when the API returns an unsuccessful HTTP response.

it("should display error message when API request fails", async () => {
    vi.stubGlobal(
        "fetch",
        vi.fn().mockResolvedValue({
            ok: false,
            status: 500
        })
    );
    render(<UserList />);
    expect(
        await screen.findByRole("alert")
    ).toHaveTextContent("Failed to fetch users");
});

This test verifies that the component displays an appropriate error message when the server responds with an HTTP error.

8. Test Network Failure

An API request may also fail because of network problems. In this case, fetch() rejects its Promise.

it("should handle network errors", async () => {
    vi.stubGlobal(
        "fetch",
        vi.fn().mockRejectedValue(
            new Error("Network error")
        )
    );
    render(<UserList />);
    expect(
        await screen.findByRole("alert")
    ).toHaveTextContent("Network error");
});

Difference:

  • HTTP error: The server responds, but the response indicates failure.
  • Network error: The request fails before a usable HTTP response is received.

9. Test Empty API Response

Sometimes the API succeeds but returns an empty array. We should test this scenario separately.

it("should display empty message when API returns no users", async () => {
    vi.stubGlobal(
        "fetch",
        vi.fn().mockResolvedValue({
            ok: true,
            json: async () => []
        })
    );
    render(<UserList />);
    expect(
        await screen.findByText("No users found")
    ).toBeInTheDocument();
});

This verifies that the component handles empty results instead of displaying an empty list without explanation.

10. Test Retry Functionality

When an API request fails, the component provides a Retry button. We should test whether clicking it triggers another API request.

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, it, vi } from "vitest";
import UserList from "./UserList";
it("should retry API request after failure", async () => {
    const user = userEvent.setup();
    const mockFetch = vi.fn()
        .mockResolvedValueOnce({
            ok: false,
            status: 500
        })
        .mockResolvedValueOnce({
            ok: true,
            json: async () => [
                { id: 1, name: "John" }
            ]
        });
    vi.stubGlobal("fetch", mockFetch);
    render(<UserList />);
    expect(
        await screen.findByRole("alert")
    ).toBeInTheDocument();
    await user.click(
        screen.getByRole("button", { name: "Retry" })
    );
    expect(
        await screen.findByText("John")
    ).toBeInTheDocument();
    expect(mockFetch).toHaveBeenCalledTimes(2);
});

Explanation:

  1. The first API request returns an HTTP error.
  2. The component displays the error message.
  3. The user clicks Retry.
  4. The second API request succeeds.
  5. The component displays the returned user.

11. Test Loading State During Retry

It is also important to verify that the loading message appears when a retry request is in progress.

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, it, vi } from "vitest";
import UserList from "./UserList";
it("should show loading state during retry", async () => {
    const user = userEvent.setup();
    let resolveRequest;
    const pendingRequest = new Promise(resolve => {
        resolveRequest = resolve;
    });
    const mockFetch = vi.fn()
        .mockResolvedValueOnce({
            ok: false,
            status: 500
        })
        .mockReturnValueOnce(pendingRequest);
    vi.stubGlobal("fetch", mockFetch);
    render(<UserList />);
    await screen.findByRole("alert");
    await user.click(
        screen.getByRole("button", { name: "Retry" })
    );
    expect(
        screen.getByRole("status")
    ).toHaveTextContent("Loading users...");
    resolveRequest({
        ok: true,
        json: async () => [
            { id: 1, name: "John" }
        ]
    });
    expect(
        await screen.findByText("John")
    ).toBeInTheDocument();
});

This verifies the loading behavior during a retry operation.

12. Method 2: Mock API Requests Using MSW

Mock Service Worker (MSW) is a popular approach for testing components that communicate with APIs.

Instead of mocking fetch() directly, MSW intercepts network requests and returns controlled responses.

Why use MSW?

  • Tests API behavior at the network boundary.
  • Works with fetch() and Axios.
  • Supports successful and unsuccessful responses.
  • Allows reusable API handlers.
  • Reduces direct mocking of individual API functions.

Install MSW

npm install -D msw

Create API handlers

src/mocks/handlers.js

import { http, HttpResponse } from "msw";
export const handlers = [
    http.get("/api/users", () => {
        return HttpResponse.json([
            { id: 1, name: "John" },
            { id: 2, name: "David" }
        ]);
    })
];

Configure the test server

src/mocks/server.js

import { setupServer } from "msw/node";
import { handlers } from "./handlers";
export const server = setupServer(...handlers);

Configure test setup

src/setupTests.js

import "@testing-library/jest-dom/vitest";
import { beforeAll, afterAll, afterEach } from "vitest";
import { server } from "./mocks/server";
beforeAll(() => server.listen({
    onUnhandledRequest: "error"
}));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Make sure this setup file is configured in Vitest.

Test successful API response with MSW

import { render, screen } from "@testing-library/react";
import { expect, it } from "vitest";
import UserList from "./UserList";
it("should display users from mocked API", async () => {
    render(<UserList />);
    expect(
        await screen.findByText("John")
    ).toBeInTheDocument();
    expect(
        screen.getByText("David")
    ).toBeInTheDocument();
});

MSW intercepts the request to /api/users and returns the configured user list.

Test API error response with MSW

import { http, HttpResponse } from "msw";
import { server } from "./mocks/server";
it("should display error when API returns HTTP 500", async () => {
    server.use(
        http.get("/api/users", () => {
            return new HttpResponse(null, {
                status: 500
            });
        })
    );
    render(<UserList />);
    expect(
        await screen.findByRole("alert")
    ).toHaveTextContent("Failed to fetch users");
});

Use server.use() to override the default handler for an individual test. The afterEach() cleanup resets the handlers.

13. findBy vs waitFor vs queryBy

Method Purpose Example
getBy Find an element immediately. Throws if it is missing. getByText("John")
queryBy Check whether an element exists or is absent. queryByText("Loading")
findBy Wait for an element to appear asynchronously. findByText("John")
waitFor Wait until an assertion or condition succeeds. waitFor(() => expect(fn).toHaveBeenCalled())

14. Common Mistakes in Asynchronous Testing

1. Not Using await with findBy

Incorrect:

expect(
    screen.findByText("John")
).toBeInTheDocument();

Correct:

expect(
    await screen.findByText("John")
).toBeInTheDocument();

findBy returns a Promise, so it must be awaited.

2. Using getBy for Elements That Appear Later

Incorrect:

expect(screen.getByText("John")).toBeInTheDocument();

Correct:

expect(
    await screen.findByText("John")
).toBeInTheDocument();

3. Not Mocking API Requests

Tests should not depend on real external APIs. Use controlled mock responses or MSW to make tests predictable and repeatable.

4. Ignoring Error States

Testing only successful API responses leaves important failure scenarios untested. Include HTTP errors and network failures.

5. Forgetting to Test Loading State

Loading indicators are part of the user experience. Verify that they appear while requests are pending and disappear when requests finish.

6. Not Cleaning Up Global Mocks

When using vi.stubGlobal(), restore the original global values after each test. For example, configure vi.unstubAllGlobals() in an afterEach() hook.

15. Best Practices

  • Test loading, success, error and empty states.
  • Use findBy queries for elements that appear asynchronously.
  • Use waitFor for asynchronous assertions that are not simply element queries.
  • Use queryBy to verify that elements are absent.
  • Mock API responses instead of depending on real services.
  • Prefer MSW for realistic API-level testing.
  • Test retry functionality when the component supports it.
  • Verify that loading indicators disappear after requests finish.
  • Test network failures separately from HTTP errors.
  • Keep tests independent and predictable.

16. Interview Questions and Answers

Q1. How do you test asynchronous data fetching in React?

Mock the API request, render the component, and use asynchronous queries such as findBy to verify that the returned data appears.

Q2. What is the difference between getBy and findBy?

getBy searches immediately and throws if the element is missing. findBy waits for the element to appear and returns a Promise.

Q3. What is waitFor() used for?

waitFor() repeatedly checks an assertion until it passes or the timeout is reached. It is useful for waiting for asynchronous behavior that is not directly represented by an element query.

Q4. How do you test loading states?

Keep the mocked API request pending using a controlled Promise, render the component, and verify that the loading indicator is displayed.

Q5. How do you test API failures?

Mock an unsuccessful HTTP response or reject the API Promise, then verify that the component displays the expected error message.

Q6. What is MSW?

Mock Service Worker is a library that intercepts network requests and provides controlled responses during tests.

Q7. Why is MSW often preferred over directly mocking fetch?

MSW works at the network boundary, making tests closer to real application behavior. It also supports reusable handlers and different response scenarios.

Q8. How do you test an empty API response?

Mock the API to return an empty array and verify that the component displays an appropriate empty-state message.

Q9. How do you test retry functionality?

Configure the first API request to fail and the second request to succeed. Click Retry and verify that the new data is displayed.

Q10. What is the difference between an HTTP error and a network error?

An HTTP error means the server returned an unsuccessful status code. A network error means the request failed before receiving a usable HTTP response.

17. Key Takeaway

Testing asynchronous React components is mainly about verifying how the UI behaves while waiting for data and after the request completes.

  1. Mock API requests using Vitest or MSW.
  2. Test the loading state.
  3. Test successful API responses.
  4. Test HTTP and network errors.
  5. Test empty responses.
  6. Test retry functionality.
  7. Use findBy and waitFor appropriately.

Remember: Do not test only whether an API request succeeds. Test every user-visible state that can occur during the complete data-fetching lifecycle.

🔙
How to Test Components That Use Context :👈 👉:How to Write Integration Tests for React Pages

Comments and Discussion