Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 38 ยท Testing and DevTools

Testing Queries and Mutations

Test components and hooks that use TanStack Query: a fresh QueryClient per test, retry off, a wrapper, waitFor, mocking fetch or MSW, and testing loading, error and mutation flows.

Components that use TanStack Query depend on a QueryClient, on timing and on a network. Tests become flaky if they share a cache, wait for real retries or call a real server. A few simple rules make query tests fast and reliable. This lesson explains the rules, shows the real Vitest and Testing Library code (read-only, because those tools are not available in the page) and runs hand-written stand-ins so you can watch the ideas work.

The five rules

  1. A new QueryClient for every test. The cache lives in the client; sharing one leaks data from one test into the next.
  2. Turn retries off. The default is three retries with exponential backoff, so a failing query takes about 7 seconds to report an error. Use retry: false in the test client.
  3. Unmount and discard. Testing Library unmounts after each test; throw the client away with it. Each unused query schedules a garbage-collection timer (gcTime, 5 minutes), so setting gcTime: 0 in the test client keeps the runner from waiting on timers.
  4. Wrap in QueryClientProvider. Use a helper so every test does not repeat it.
  5. Mock the network, not TanStack Query. Replace fetch (or use MSW to intercept at the network layer). Mocking useQuery itself tests the mock rather than your component.

A test wrapper

JSX
// test-utils.jsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

export function createWrapper() {
  const queryClient = new QueryClient({
    defaultOptions: { queries: { retry: false } },
  });
  return function Wrapper({ children }) {
    return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
  };
}

Testing a component (read-only)

JSX
// profile.test.jsx
import { render, screen } from "@testing-library/react";
import { expect, test, vi } from "vitest";
import { createWrapper } from "./test-utils";
import Profile from "./Profile";

test("shows the user's name", async () => {
  vi.stubGlobal("fetch", vi.fn(async () => ({ ok: true, json: async () => ({ name: "Ada" }) })));

  render(<Profile id={1} />, { wrapper: createWrapper() });

  expect(screen.getByText(/loading/i)).toBeInTheDocument();
  expect(await screen.findByText("Ada")).toBeInTheDocument();   // waits up to 1 s
});

test("shows an error message", async () => {
  vi.stubGlobal("fetch", vi.fn(async () => ({ ok: false, status: 500 })));
  render(<Profile id={1} />, { wrapper: createWrapper() });
  expect(await screen.findByText(/something went wrong/i)).toBeInTheDocument();
});

findBy... queries (or waitFor) retry until the element appears, which is how you wait for the query to resolve. Never setTimeout in a test.

Testing a hook (read-only)

JSX
import { renderHook, waitFor } from "@testing-library/react";
import { useTodos } from "./useTodos";

test("useTodos returns the list", async () => {
  const { result } = renderHook(() => useTodos(), { wrapper: createWrapper() });
  await waitFor(() => expect(result.current.isSuccess).toBe(true));
  expect(result.current.data).toHaveLength(3);
});

A runnable stand-in test runner

Because Vitest is not installed here, the example below defines a tiny test function and a findByText helper, mounts the real component with real TanStack Query into a detached node, and uses a fake fetch. The structure is exactly what you would write with Testing Library.

A component test, hand-made runner

Three tests pass and the last one fails on purpose to show the report. Notice that the second client in "does not share cache" fetches again: that is the fresh-client rule at work. Without it the second render would have found the cached user and calls would be 1.

Testing mutations

A mutation test clicks a button, waits for the result and checks both the UI and the request:

JSX
test("adds a todo", async () => {
  const fetchMock = vi.fn(async () => ({ ok: true, json: async () => ({ id: 9, text: "Buy milk" }) }));
  vi.stubGlobal("fetch", fetchMock);
  render(<Todos />, { wrapper: createWrapper() });

  await userEvent.type(screen.getByRole("textbox"), "Buy milk");
  await userEvent.click(screen.getByRole("button", { name: /add/i }));

  expect(await screen.findByText("Buy milk")).toBeInTheDocument();
  expect(fetchMock).toHaveBeenCalledWith("/api/todos", expect.objectContaining({ method: "POST" }));
});

To test optimistic updates, make the fake request wait on a promise you control. Assert that the optimistic row is visible while the promise is pending, then reject it and assert the rollback:

JSX
let rejectRequest;
vi.stubGlobal("fetch", () => new Promise((_, reject) => { rejectRequest = reject; }));
/* click toggle */
expect(screen.getByRole("checkbox")).toBeChecked();             // optimistic
rejectRequest(new Error("fail"));
await waitFor(() => expect(screen.getByRole("checkbox")).not.toBeChecked()); // rolled back

Testing the cache logic directly

Optimistic update logic, selectors and query options can be tested without React, using only the client. The cache methods are synchronous and fast.

JS Testing cache logic with QueryClient

Press Run (or Ctrl + Enter) to see the console output here.

No output.

These tests run in milliseconds. Keep the bulk of your coverage here and in component tests, and add a few end-to-end tests with a real browser for the most important flows.

Mocking at the network layer with MSW

Mock Service Worker intercepts fetch calls at the network level, so your app code and TanStack Query run unchanged, and the same handlers work in tests, Storybook and the browser:

JavaScript
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";

const server = setupServer(
  http.get("/api/users/:id", ({ params }) => HttpResponse.json({ id: params.id, name: "Ada" })),
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test("error path", async () => {
  server.use(http.get("/api/users/:id", () => new HttpResponse(null, { status: 500 })));
  /* render and assert the error UI */
});

MSW is not available in the page; the code above is read-only.

Common testing mistakes

  • One global QueryClient. Tests pass alone and fail together.
  • Leaving retries on. Error tests take seconds and time out.
  • Asserting synchronously. The first render is always the loading state; wait with findBy/waitFor.
  • Mocking the hook. Mock the network instead.
  • Forgetting to await the final state and ending the test before a state update, which causes "not wrapped in act" warnings.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why create a new QueryClient for each test?

    The cache lives in the client. A shared client lets a previous test's data change the next test's behaviour.
  2. 2. Why set retry: false in tests?

    The default is three retries with exponential delay; tests should see the error immediately.
  3. 3. How should a test wait for a query to resolve?

    findBy and waitFor poll until the assertion passes or a timeout expires, so tests are quick and not timing-dependent.
  4. 4. What is the best thing to mock in a component test?

    Mocking the network keeps the real TanStack Query behaviour (loading, errors, caching) under test.

Summary

  • Use a fresh QueryClient with retry: false per test, inside a shared wrapper.
  • Mock the network (stubbed fetch or MSW), never useQuery.
  • Wait with findBy or waitFor; test loading, success, error and mutation flows.
  • Test optimistic updates by holding the request open with a controlled promise.
  • Unit-test cache logic directly with QueryClient for fast, React-free checks.

Next: Debugging and Production Monitoring