Sub topic 16
Testing components that use TanStack Query
This chapter assumes you can write component tests with Vitest (or Jest) and React Testing Library, and that you know useQuery and QueryClientProvider from earlier chapters. The examples use Vitest.
What makes these tests different
A component that calls useQuery needs a QueryClientProvider above it. It also fetches asynchronously, so the first render shows the pending state. Three rules cover most of the work:
- Create a new
QueryClientfor every test, so one test's cache never leaks into the next. - Turn off retries. By default a failed query retries three times with backoff, so an error test would wait several seconds before the error state appears.
- Replace the network. Stub
fetchor intercept requests with a tool such as Mock Service Worker (MSW). Do not mockuseQueryitself, because then you are no longer testing the real states.
A render helper
Put the provider setup in one helper so every test gets the same configuration.
import { render } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactElement } from 'react'
export function renderWithClient(ui: ReactElement) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
return render(
<QueryClientProvider client={client}>{ui}</QueryClientProvider>,
)
}Testing success and error states
This test file exercises the Todos component from the useQuery chapter. It assumes Todos is exported from ./Todos and that the helper above is saved as ./test-utils.tsx.
import { screen } from '@testing-library/react'
import { afterEach, expect, test, vi } from 'vitest'
import { Todos } from './Todos'
import { renderWithClient } from './test-utils'
afterEach(() => {
vi.unstubAllGlobals()
})
test('shows todos after loading', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => [{ id: 1, title: 'Write tutorial', done: false }],
}),
)
renderWithClient(<Todos />)
expect(screen.getByText('Loading...')).toBeDefined()
expect(await screen.findByText('Write tutorial')).toBeDefined()
})
test('shows an error message when the request fails', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({ ok: false, status: 500 }),
)
renderWithClient(<Todos />)
expect(await screen.findByText(/Request failed: 500/)).toBeDefined()
})The findBy queries wait until the element appears, which gives the query time to settle. Use getBy for the first synchronous render, where the pending state is already on screen.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Error test times out | Default retries are still on | Set `retry: false` on the test client |
| Data from one test appears in another | A shared `QueryClient` | Create the client inside the helper, once per test |
| "No QueryClient set" error | Component rendered without a provider | Render through `renderWithClient` |
| Assertion fails on first render | Data has not arrived yet | Use `findBy` or `waitFor`, not `getBy` |
For mutations, assert on what the user sees after the action. Click the button, then wait for the refetched list or the changed label. Stub fetch for both the POST and the follow-up GET that invalidation triggers.
Exercise
A test for a failing request waits several seconds and then times out, even though the mocked fetch returns { ok: false, status: 500 } immediately. What is the cause, and what is the fix?
Show answer
The query function throws, but TanStack Query retries failed queries three times with exponential backoff before it reports the error state. The test finishes waiting before that happens. Create the test QueryClient with defaultOptions: { queries: { retry: false } } so the error appears right away.