Sub topic 16
Testing components that use TanStack Query
This chapter shows how to test React components that call useQuery and useMutation. It assumes you can write component tests with Vitest (or Jest) and React Testing Library. You should also know the query, mutation, and invalidation material from the earlier chapters. The examples use Vitest with the jsdom environment, @testing-library/react, and @testing-library/user-event. The same ideas apply to Jest.
What to test and what to leave alone
Test what the user sees: loading text, rendered data, error messages, and the list refreshing after a change. Do not mock useQuery itself. A mocked hook skips the query cache, the status transitions, and invalidation, which are the parts that break in real apps.
Instead, run the real QueryClient and replace only the network. The component then goes through its real states, and your assertions cover real behavior.
A shared render helper
Every test needs a provider. Put the setup in one helper so tests stay short.
// test-utils.tsx
import { render } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactElement, ReactNode } from 'react'
export function createTestQueryClient() {
return new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
}
export function renderWithClient(ui: ReactElement) {
const client = createTestQueryClient()
const result = render(
<QueryClientProvider client={client}>{ui}</QueryClientProvider>,
)
return { client, ...result }
}
export function createWrapper() {
const client = createTestQueryClient()
return function Wrapper({ children }: { children: ReactNode }) {
return <QueryClientProvider client={client}>{children}</QueryClientProvider>
}
}Two settings matter here.
- A new client per test. The cache lives on the
QueryClient. If tests share a client, data from one test leaks into the next and results depend on test order. retry: false. By default a failing query retries three times with growing delays. A test that expects an error would wait several seconds, andfindBy*queries give up after one second. Turning retries off makes the error state appear right away.
Faking the network
The simplest approach is to spy on fetch and return real Response objects. This keeps your query functions untouched, including their res.ok check.
// helpers.ts
export function json(body: unknown, status = 200) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
})
}You can also use Mock Service Worker (MSW), which intercepts requests at the network layer and is closer to production. Node's fetch cannot resolve relative URLs such as /api/todos. With MSW, use absolute URLs or set a base URL in your test environment.
Testing the pending, success, and error states
This test file assumes Todos and AddTodo from the earlier chapters are exported from ./components.
// todos.test.tsx
import { afterEach, describe, expect, it, vi } from 'vitest'
import { screen } from '@testing-library/react'
import { renderWithClient } from './test-utils'
import { json } from './helpers'
import { Todos } from './components'
afterEach(() => {
vi.restoreAllMocks()
})
describe('Todos', () => {
it('shows loading, then the todos', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
json([{ id: 1, title: 'Learn Query', done: false }]),
)
renderWithClient(<Todos />)
expect(screen.getByText('Loading...')).toBeDefined()
expect(await screen.findByText('Learn Query')).toBeDefined()
})
it('shows an error message when the request fails', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue(json({}, 500))
renderWithClient(<Todos />)
expect(
await screen.findByText('Something went wrong: Request failed: 500'),
).toBeDefined()
})
})The first assertion is synchronous because the component renders Loading... on the first render, before the promise settles. After that, use findBy* queries, which retry until the element appears or the timeout passes. Avoid fixed setTimeout waits.
Testing a mutation and its invalidation
A mutation test should prove the whole loop: the request is sent, the affected query is invalidated, and the list refetches and shows the change. A small stateful fake server makes this easy to check.
// add-todo.test.tsx
import { afterEach, expect, it, vi } from 'vitest'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWithClient } from './test-utils'
import { json } from './helpers'
import { Todos, AddTodo } from './components'
type Todo = { id: number; title: string; done: boolean }
afterEach(() => {
vi.restoreAllMocks()
})
it('refetches the list after a todo is added', async () => {
let todos: Todo[] = [{ id: 1, title: 'Learn Query', done: false }]
const fetchSpy = vi
.spyOn(globalThis, 'fetch')
.mockImplementation(async (_input, init) => {
if (init?.method === 'POST') {
const { title } = JSON.parse(String(init.body))
const created = { id: 2, title, done: false }
todos = [...todos, created]
return json(created, 201)
}
return json(todos)
})
renderWithClient(
<>
<Todos />
<AddTodo />
</>,
)
await screen.findByText('Learn Query')
await userEvent.click(screen.getByRole('button', { name: 'Add todo' }))
expect(await screen.findByText('Write tutorial')).toBeDefined()
const methods = fetchSpy.mock.calls.map(([, init]) => init?.method ?? 'GET')
expect(methods).toEqual(['GET', 'POST', 'GET'])
})The final GET in the call list is the refetch that invalidateQueries triggered. If you remove the onSuccess invalidation from AddTodo, this test fails because the new title never appears. That is the regression this test is meant to catch.
Testing custom hooks with renderHook
If you wrap a query in a custom hook, you can test it without a component. renderHook takes the provider through its wrapper option.
// use-todos.test.tsx
import { afterEach, expect, it, vi } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { useQuery } from '@tanstack/react-query'
import { createWrapper } from './test-utils'
import { json } from './helpers'
function useTodos() {
return useQuery({
queryKey: ['todos'],
queryFn: async () => {
const res = await fetch('/api/todos')
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json() as Promise<{ id: number; title: string }[]>
},
})
}
afterEach(() => {
vi.restoreAllMocks()
})
it('resolves with data', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
json([{ id: 1, title: 'Learn Query' }]),
)
const { result } = renderHook(() => useTodos(), { wrapper: createWrapper() })
await waitFor(() => expect(result.current.isSuccess).toBe(true))
expect(result.current.data).toHaveLength(1)
})Always read result.current inside the waitFor callback. The hook returns a new object on every render, so a value you saved earlier is stale.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Error test times out | Default retries are still on | Set `retry: false` in the test client |
| Data from a previous test appears | A client is shared across tests | Create a client per test |
| `No QueryClient set` error | Component rendered without a provider | Use `renderWithClient` or the `wrapper` option |
| `act` warnings after the test ends | The test finished before the query settled | `await` a `findBy*` or `waitFor` for the final state |
| `Invalid URL` from `fetch` | Node cannot resolve `/api/...` | Spy on `fetch`, or use absolute URLs with MSW |
Testing optimistic updates
For an optimistic update, test two outcomes. In the success case, the UI changes and the final refetch agrees with the server. In the failure case, the UI returns to the previous value after the mutation fails. Make the fake server reject the PATCH with a 500, click the checkbox, and assert that the todo ends up unchecked. The rollback in onError and the refetch in onSettled both run, so the final state should match the server's unchanged data.
Exercise
A test for a component that shows an error message passes locally only after about seven seconds and sometimes fails with a timeout on findByText. The fake fetch returns a 500 response. What is the most likely cause, and what is the fix?
Show answer
The test's QueryClient still uses the default retry behavior, which retries a failed query three times with exponential backoff before it enters the error state. The error message appears only after those retries finish, which is slower than the one-second default timeout of findBy*. Create the test client with defaultOptions: { queries: { retry: false } } so the query fails immediately.
Exercise
Why should each test create its own QueryClient instead of exporting one shared client from a test utilities file?
Show answer
The QueryClient owns the cache. A shared client keeps query data between tests, so a later test can render cached data from an earlier one, skip the loading state, or see results that depend on test order. A fresh client per test gives each test an empty cache.