TanStack Query Testing
You are an expert QA engineer specializing in TanStack Query (React Query) testing patterns. When the user asks you to write, review, debug, or set up tests for data fetching hooks, mutations, cache behavior, or optimistic updates built with TanStack Query, follow these detailed instructions. You understand QueryClient configuration, query keys, stale time, cache time, retry behavior, query invalidation, and the full TanStack Query lifecycle.
Core Principles
- Wrapper-First Testing -- Every TanStack Query test requires a
QueryClientProvider wrapper. Create a dedicated test utility that provides a fresh QueryClient per test to prevent cache leakage between tests.
- MSW for Network Mocking -- Use Mock Service Worker (MSW) to intercept network requests at the service worker level. Avoid mocking
fetch directly -- MSW provides more realistic behavior and catches URL/method mismatches.
- waitFor Over Timeouts -- TanStack Query is inherently asynchronous. Always use
waitFor from Testing Library to wait for state transitions. Never use setTimeout or fixed delays.
- Cache Isolation -- Each test must use a fresh
QueryClient instance with caching disabled or gcTime: 0. Shared cache between tests is the number one source of flaky TanStack Query tests.
- Test State Transitions -- Query hooks transition through loading, success, error, and stale states. Test each transition explicitly rather than only testing the final state.
- Mutation Side Effects -- Mutations trigger cache invalidation, optimistic updates, and onSuccess/onError callbacks. Test each side effect independently.
- Type-Safe Query Keys -- Use typed query key factories to ensure consistency between components and tests. Mismatched query keys cause subtle cache bugs.
When to Use This Skill
- When testing custom hooks built with
useQuery, useMutation, or useInfiniteQuery
- When verifying cache invalidation and refetch behavior
- When testing optimistic updates and rollback logic
- When testing suspense boundaries with TanStack Query
- When testing prefetching on hover or route transition
- When testing error handling, retry logic, and fallback UI
- When testing infinite scroll/pagination with
useInfiniteQuery
- When integrating MSW for API mocking in TanStack Query tests
Project Structure
project-root/
├── src/
│ ├── api/
│ │ ├── client.ts # API client (fetch/axios wrapper)
│ │ ├── users.ts # User API functions
│ │ ├── posts.ts # Post API functions
│ │ └── comments.ts # Comment API functions
│ ├── hooks/
│ │ ├── useUser.ts # User query hook
│ │ ├── useUsers.ts # Users list query hook
│ │ ├── usePosts.ts # Posts query hook
│ │ ├── useCreatePost.ts # Create post mutation
│ │ ├── useUpdatePost.ts # Update post mutation (optimistic)
│ │ ├── useDeletePost.ts # Delete post mutation
│ │ ├── useInfiniteComments.ts # Infinite scroll comments
│ │ └── queryKeys.ts # Centralized query key factory
│ ├── components/
│ │ ├── UserProfile.tsx # User profile component
│ │ ├── PostList.tsx # Post list with mutations
│ │ ├── PostEditor.tsx # Post editor with optimistic updates
│ │ └── CommentFeed.tsx # Infinite scroll comments
│ └── providers/
│ └── QueryProvider.tsx # App-level QueryClientProvider
│
├── tests/
│ ├── setup/
│ │ ├── test-utils.tsx # Test wrapper & utilities
│ │ ├── msw-handlers.ts # MSW request handlers
│ │ ├── msw-server.ts # MSW server setup
│ │ └── test-data.ts # Shared test data
│ ├── hooks/
│ │ ├── useUser.test.ts # User hook tests
│ │ ├── useUsers.test.ts # Users list tests
│ │ ├── usePosts.test.ts # Posts hook tests
│ │ ├── useCreatePost.test.ts # Create mutation tests
│ │ ├── useUpdatePost.test.ts # Optimistic update tests
│ │ ├── useDeletePost.test.ts # Delete mutation tests
│ │ └── useInfiniteComments.test.ts # Infinite query tests
│ ├── components/
│ │ ├── UserProfile.test.tsx # User profile integration
│ │ ├── PostList.test.tsx # Post list integration
│ │ └── CommentFeed.test.tsx # Infinite scroll integration
│ └── cache/
│ ├── invalidation.test.ts # Cache invalidation tests
│ ├── prefetching.test.ts # Prefetch tests
│ └── stale-time.test.ts # Stale/cache time tests
│
├── vitest.config.ts
└── package.json
Source Code Setup
Query Key Factory
export const queryKeys = {
users: {
all: ['users'] as const,
lists: () => [...queryKeys.users.all, 'list'] as const,
list: (filters: Record<string, unknown>) =>
[...queryKeys.users.lists(), filters] as const,
details: () => [...queryKeys.users.all, 'detail'] as const,
detail: (id: number) => [...queryKeys.users.details(), id] as const,
},
posts: {
all: ['posts'] as const,
lists: () => [...queryKeys.posts.all, 'list'] as const,
list: () =>
[...queryKeys..(), filters] ,
: [...queryKeys.., ] ,
: [...queryKeys..(), id] ,
},
: {
: [] ,
: [...queryKeys.., , postId] ,
:
[...queryKeys.., , postId] ,
},
} ;
API Functions
export interface User {
id: number;
name: string;
email: string;
role: string;
}
const API_BASE = '/api';
export async function fetchUser(id: number): Promise<User> {
const response = await fetch(`${API_BASE}/users/${id}`);
if (!response.ok) {
throw new Error(`Failed to fetch user: ${response.status}`);
}
return response.json();
}
export async function fetchUsers(filters?: {
role?: string;
page?: number;
}): Promise<{ users: User[]; total: number }> {
const params = new URLSearchParams();
(filters?.) params.(, filters.);
(filters?.) params.(, (filters.));
response = ();
(!response.) {
();
}
response.();
}
export interface Post {
id: number;
title: string;
content: string;
authorId: number;
published: boolean;
createdAt: string;
}
export interface CreatePostInput {
title: string;
content: string;
authorId: number;
}
export interface UpdatePostInput {
title?: string;
content?: string;
published?: boolean;
}
const API_BASE = '/api';
export async function fetchPosts(filters?: {
authorId?: number;
published?: boolean;
}): Promise<Post[]> {
const params = new URLSearchParams();
if (filters?.authorId) params.set('authorId', (filters.));
(filters?. !== ) params.(, (filters.));
response = ();
(!response.) ();
response.();
}
(): <> {
response = ();
(!response.) ();
response.();
}
(): <> {
response = (, {
: ,
: { : },
: .(input),
});
(!response.) ();
response.();
}
(): <> {
response = (, {
: ,
: { : },
: .(input),
});
(!response.) ();
response.();
}
(): <> {
response = (, { : });
(!response.) ();
}
Query Hooks
import { useQuery } from '@tanstack/react-query';
import { fetchUser } from '../api/users';
import { queryKeys } from './queryKeys';
export function useUser(id: number) {
return useQuery({
queryKey: queryKeys.users.detail(id),
queryFn: () => fetchUser(id),
enabled: id > 0,
staleTime: 5 * 60 * 1000,
});
}
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { createPost, type CreatePostInput, type Post } from '../api/posts';
import { queryKeys } from './queryKeys';
export function useCreatePost() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (input: CreatePostInput) => createPost(input),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: queryKeys.posts.lists() });
},
});
}
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { updatePost, type UpdatePostInput, type Post } from '../api/posts';
import { queryKeys } from './queryKeys';
export function useUpdatePost(postId: number) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (input: UpdatePostInput) => updatePost(postId, input),
onMutate: async (newData) => {
await queryClient.cancelQueries({ queryKey: queryKeys.posts.detail(postId) });
const previousPost = queryClient.getQueryData<Post>(
queryKeys.posts.detail(postId),
);
queryClient.setQueryData<Post>(queryKeys..(postId),
old ? { ...old, ...newData } : old,
);
{ previousPost };
},
: {
(context?.) {
queryClient.(
queryKeys..(postId),
context.,
);
}
},
: {
queryClient.({ : queryKeys..(postId) });
queryClient.({ : queryKeys..() });
},
});
}
import { useInfiniteQuery } from '@tanstack/react-query';
import { queryKeys } from './queryKeys';
interface Comment {
id: number;
body: string;
authorId: number;
postId: number;
createdAt: string;
}
interface CommentsPage {
comments: Comment[];
nextCursor: number | null;
total: number;
}
async function fetchComments(postId: number, cursor: number = 0): Promise<CommentsPage> {
const response = await fetch(`/api/posts/${postId}/comments?cursor=${cursor}&limit=10`);
if (!response.ok) throw new Error('Failed to fetch comments');
return response.json();
}
() {
({
: queryKeys..(postId),
: (postId, pageParam),
: ,
: lastPage.,
: postId > ,
});
}
Test Infrastructure
Test Utilities
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, type RenderOptions } from '@testing-library/react';
import { renderHook, type RenderHookOptions } from '@testing-library/react';
function createTestQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
gcTime: 0,
staleTime: 0,
},
mutations: {
retry: false,
},
},
});
}
export function createWrapper() {
const queryClient = createTestQueryClient();
return function Wrapper() {
(
);
};
}
() {
queryClient = ();
= () => (
);
{
...(ui, { wrapper, ...options }),
queryClient,
};
}
renderHookWithClient<>(
: ,
?: <<>, >,
) {
queryClient = ();
= () => (
);
{
...(hook, { wrapper, ...options }),
queryClient,
};
}
MSW Setup
import { setupServer } from 'msw/node';
import { handlers } from './msw-handlers';
export const server = setupServer(...handlers);
import { http, HttpResponse, delay } from 'msw';
import { testUsers, testPosts, testComments } from './test-data';
export const handlers = [
http.get('/api/users', ({ request }) => {
const url = new URL(request.url);
const role = url.searchParams.get('role');
let users = testUsers;
if (role) {
users = users.filter((u) => u.role === role);
}
return HttpResponse.json({ users, total: users.length });
}),
http.get('/api/users/:id', ({ params }) => {
const id = Number(params.id);
const user = testUsers.find((u) => u.id === id);
if (!user) {
return new (, { : });
}
.(user);
}),
http.(, {
url = (request.);
authorId = url..();
published = url..();
posts = testPosts;
(authorId) posts = posts.( p. === (authorId));
(published !== ) posts = posts.( p. === (published === ));
.(posts);
}),
http.(, {
id = (params.);
post = testPosts.( p. === id);
(!post) (, { : });
.(post);
}),
http.(, ({ request }) => {
body = ( request.()) <, >;
newPost = {
: testPosts. + ,
...body,
: ,
: ().(),
};
.(newPost, { : });
}),
http.(, ({ params, request }) => {
id = (params.);
body = ( request.()) <, >;
post = testPosts.( p. === id);
(!post) (, { : });
updated = { ...post, ...body };
.(updated);
}),
http.(, {
id = (params.);
post = testPosts.( p. === id);
(!post) (, { : });
(, { : });
}),
http.(, {
postId = (params.);
url = (request.);
cursor = (url..() || );
limit = (url..() || );
allComments = testComments.( c. === postId);
startIndex = cursor;
pageComments = allComments.(startIndex, startIndex + limit);
nextCursor = startIndex + limit < allComments. ? startIndex + limit : ;
.({
: pageComments,
nextCursor,
: allComments.,
});
}),
];
Test Data
export const testUsers = [
{ id: 1, name: 'Alice Johnson', email: 'alice@test.com', role: 'admin' },
{ id: 2, name: 'Bob Smith', email: 'bob@test.com', role: 'user' },
{ id: 3, name: 'Charlie Brown', email: 'charlie@test.com', role: 'user' },
];
export const testPosts = [
{
id: 1,
title: 'First Post',
content: 'Content of first post',
authorId: 1,
published: true,
createdAt: '2024-01-01T00:00:00Z',
},
{
id: 2,
title: 'Second Post',
content: 'Content of second post',
authorId: 1,
published: false,
createdAt: '2024-01-02T00:00:00Z',
},
{
id: ,
: ,
: ,
: ,
: ,
: ,
},
];
testComments = .({ : }, ({
: i + ,
: ,
: (i % ) + ,
: ,
: (, , i + ).(),
}));
Vitest Configuration
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: 'jsdom',
setupFiles: ['./tests/setup/vitest-setup.ts'],
include: ['tests/**/*.test.{ts,tsx}'],
coverage: {
provider: 'v8',
include: ['src/hooks/**', 'src/components/**'],
},
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@tests': path.resolve(__dirname, './tests'),
},
},
});
import '@testing-library/jest-dom/vitest';
import { server } from './msw-server';
import { afterAll, afterEach, beforeAll } from 'vitest';
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Hook Tests
useUser Hook Tests
import { describe, it, expect } from 'vitest';
import { waitFor } from '@testing-library/react';
import { renderHookWithClient } from '../setup/test-utils';
import { useUser } from '../../src/hooks/useUser';
import { server } from '../setup/msw-server';
import { http, HttpResponse } from 'msw';
describe('useUser', () => {
it('should fetch user by ID', async () => {
const { result } = renderHookWithClient(() => useUser(1));
expect(result.current.isLoading).toBe(true);
expect(result.current.data).toBeUndefined();
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result..).({
: ,
: ,
: ,
: ,
});
});
(, () => {
{ result } = ( ());
(result..).();
(result..).();
(result..).();
});
(, () => {
server.(
http.(, {
(, { : });
}),
);
{ result } = ( ());
( {
(result..).();
});
(result..).();
(result..!.).();
});
(, () => {
server.(
http.(, {
.();
}),
);
{ result } = ( ());
( {
(result..).();
});
(result..).();
});
(, () => {
: [] = [];
{ result } = ( {
query = ();
states.(query.);
query;
});
( {
(result..).();
});
(states).();
(states).();
});
});
Mutation Tests
import { describe, it, expect, vi } from 'vitest';
import { waitFor } from '@testing-library/react';
import { renderHookWithClient } from '../setup/test-utils';
import { useCreatePost } from '../../src/hooks/useCreatePost';
import { queryKeys } from '../../src/hooks/queryKeys';
import { server } from '../setup/msw-server';
import { http, HttpResponse } from 'msw';
describe('useCreatePost', () => {
it('should create a new post', async () => {
const { result } = renderHookWithClient(() => useCreatePost());
result.current.mutate({
title: 'New Post',
content: 'New content',
authorId: 1,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
(result..).({
: ,
: ,
: ,
});
});
(, () => {
{ result, queryClient } = ( ());
invalidateSpy = vi.(queryClient, );
result..({
: ,
: ,
: ,
});
( {
(result..).();
});
(invalidateSpy).({
: queryKeys..(),
});
});
(, () => {
server.(
http.(, {
.({ : }, { : });
}),
);
{ result } = ( ());
result..({
: ,
: ,
: ,
});
( {
(result..).();
});
(result..).();
});
(, () => {
{ result } = ( ());
(result..).();
result..({
: ,
: ,
: ,
});
(result..).();
( {
(result..).();
});
(result..).();
});
});
Optimistic Update Tests
import { describe, it, expect } from 'vitest';
import { waitFor } from '@testing-library/react';
import { renderHookWithClient } from '../setup/test-utils';
import { useUpdatePost } from '../../src/hooks/useUpdatePost';
import { queryKeys } from '../../src/hooks/queryKeys';
import { testPosts } from '../setup/test-data';
import { server } from '../setup/msw-server';
import { http, HttpResponse, delay } from 'msw';
describe('useUpdatePost (Optimistic Updates)', () => {
it('should optimistically update the cache', async () => {
const { result, queryClient } = renderHookWithClient(() => useUpdatePost(1));
queryClient.setQueryData(queryKeys.posts.detail(1), testPosts[0]);
server.use(
http.patch(, ({ params, request }) => {
();
body = request.();
.({ ...testPosts[], ...body });
}),
);
result..({ : });
( {
cachedPost = queryClient.(queryKeys..()) ;
(cachedPost.).();
});
( {
(result..).();
});
});
(, () => {
{ result, queryClient } = ( ());
queryClient.(queryKeys..(), testPosts[]);
server.(
http.(, {
(, { : });
}),
);
result..({ : });
( {
(result..).();
});
cachedPost = queryClient.(queryKeys..()) ;
(cachedPost.).(testPosts[].);
});
(, () => {
{ result, queryClient } = ( ());
queryClient.(queryKeys..(), testPosts[]);
queryClient.({
: queryKeys..(),
: () => {
();
testPosts[];
},
});
result..({ : });
( {
cachedPost = queryClient.(queryKeys..()) ;
(cachedPost.).();
});
});
(, () => {
{ result, queryClient } = ( ());
queryClient.(queryKeys..(), testPosts[]);
queryClient.(queryKeys..(), testPosts);
result..({ : });
( {
(result..).();
});
detailState = queryClient.(queryKeys..());
listState = queryClient.(queryKeys..());
(detailState?.).();
(listState?.).();
});
});
Infinite Query Tests
import { describe, it, expect } from 'vitest';
import { waitFor } from '@testing-library/react';
import { renderHookWithClient } from '../setup/test-utils';
import { useInfiniteComments } from '../../src/hooks/useInfiniteComments';
describe('useInfiniteComments', () => {
it('should load first page of comments', async () => {
const { result } = renderHookWithClient(() => useInfiniteComments(1));
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data?.pages).toHaveLength(1);
expect(result.current.data?.pages[0].comments).toHaveLength(10);
});
it('should detect if there are more pages', async () => {
{ result } = ( ());
( {
(result..).();
});
(result..).();
});
(, () => {
{ result } = ( ());
( {
(result..).();
});
result..();
( {
(result..?.).();
});
(result..?.[].).();
});
(, () => {
{ result } = ( ());
( {
(result..).();
});
(result..) {
result..();
( {
(result..).();
});
}
(result..?.).();
(result..).();
allComments = result..?..( p.);
(allComments).();
});
(, () => {
{ result } = ( ());
(result..).();
});
(, () => {
{ result } = ( ());
( {
(result..).();
});
result..();
(result..).();
( {
(result..).();
});
});
});
Cache Behavior Tests
Cache Invalidation Tests
import { describe, it, expect } from 'vitest';
import { waitFor } from '@testing-library/react';
import { renderHookWithClient } from '../setup/test-utils';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { queryKeys } from '../../src/hooks/queryKeys';
import { testPosts } from '../setup/test-data';
describe('Cache Invalidation', () => {
it('should refetch when query is invalidated', async () => {
let fetchCount = 0;
const { result, queryClient } = renderHookWithClient(() =>
useQuery({
queryKey: queryKeys.posts.lists(),
queryFn: async () => {
fetchCount++;
return testPosts;
},
}),
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(fetchCount).toBe();
queryClient.({ : queryKeys..() });
( {
(fetchCount).();
});
});
(, () => {
{ queryClient } = (
({
: queryKeys..(),
: () => testPosts[],
}),
);
queryClient.(queryKeys..(), testPosts[]);
queryClient.(queryKeys..(), testPosts);
queryClient.({ : queryKeys.. });
detailState = queryClient.(queryKeys..());
listState = queryClient.(queryKeys..());
(detailState?.).();
(listState?.).();
});
(, () => {
{ queryClient } = (
({
: queryKeys..(),
: () => testPosts[],
}),
);
( {
(queryClient.(queryKeys..())).();
});
queryClient.({ : queryKeys..() });
(queryClient.(queryKeys..())).();
});
});
Prefetching Tests
import { describe, it, expect } from 'vitest';
import { waitFor } from '@testing-library/react';
import { renderHookWithClient } from '../setup/test-utils';
import { useQuery } from '@tanstack/react-query';
import { queryKeys } from '../../src/hooks/queryKeys';
import { testPosts } from '../setup/test-data';
describe('Prefetching', () => {
it('should prefetch data and serve from cache', async () => {
let fetchCount = 0;
const { queryClient } = renderHookWithClient(() => useQuery({ queryKey: ['noop'], queryFn: async () => null }));
await queryClient.prefetchQuery({
queryKey: queryKeys.posts.detail(1),
queryFn: async () => {
fetchCount++;
return testPosts[0];
},
});
expect(fetchCount).();
cached = queryClient.(queryKeys..());
(cached).(testPosts[]);
});
(, () => {
fetchCount = ;
{ result, queryClient } = ( {
({
: queryKeys..(),
: () => {
fetchCount++;
testPosts[];
},
: ,
});
});
queryClient.({
: queryKeys..(),
: () => {
fetchCount++;
testPosts[];
},
: ,
});
( {
(result..).();
});
(fetchCount).();
});
});
Component Integration Tests
PostList Component Test
import { describe, it, expect } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderWithClient } from '../setup/test-utils';
import { PostList } from '../../src/components/PostList';
import { server } from '../setup/msw-server';
import { http, HttpResponse } from 'msw';
describe('PostList Component', () => {
it('should render loading state initially', () => {
renderWithClient(<PostList />);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
});
it('should render posts after loading', async () => {
renderWithClient(<PostList />);
await waitFor(() => {
expect(screen.getByText()).();
});
(screen.()).();
});
(, () => {
server.(
http.(, {
(, { : });
}),
);
();
( {
(screen.()).();
});
});
(, () => {
user = userEvent.();
();
( {
(screen.()).();
});
deleteButtons = screen.(, { : });
user.(deleteButtons[]);
confirmButton = screen.(, { : });
user.(confirmButton);
( {
(screen.())..();
});
});
});
Best Practices
- Create a fresh QueryClient per test -- never share a QueryClient instance between tests. Cache leakage causes the most common flaky test failures.
- Disable retries in tests -- set
retry: false on the test QueryClient to avoid waiting for multiple retry attempts when testing error behavior.
- Use MSW for API mocking -- Mock Service Worker intercepts at the network level, providing realistic behavior. Avoid vi.mock('fetch') which misses URL typos and method mismatches.
- Test state transitions, not just final state -- verify loading, success, error, and stale transitions. Many UI bugs occur in intermediate states.
- Use query key factories -- centralized query keys prevent key mismatches between production code and tests. Export them and use in both.
- Test optimistic updates with delayed responses -- use MSW's
delay() to slow server responses so you can assert the optimistic cache state before the server responds.
- Test cache invalidation chains -- when a mutation invalidates multiple queries, verify all related cache entries are correctly invalidated.
- Set gcTime to 0 in test QueryClient -- prevents garbage-collected queries from interfering with subsequent tests.
- Use renderHookWithClient for hook-only tests -- when testing hooks without component UI, use
renderHook with the query wrapper for cleaner tests.
- Test the enabled option -- verify that queries with
enabled: false do not fire network requests. This catches common conditional fetching bugs.
Anti-Patterns
- Sharing QueryClient between tests -- cache from one test leaks into the next, causing false positives and random failures.
- Mocking useQuery directly -- mocking
vi.mock('@tanstack/react-query') bypasses all TanStack Query behavior. Test through the real library.
- Using setTimeout instead of waitFor -- TanStack Query async state updates are unpredictable in timing. Always use Testing Library's
waitFor.
- Not wrapping hooks in QueryClientProvider -- hooks throw if rendered without a provider. The test wrapper utility prevents this.
- Testing implementation details of the cache -- avoid asserting internal cache structure. Test observable behavior (what the hook returns).
- Forgetting to call server.resetHandlers() -- MSW handler overrides persist between tests if not reset, causing unexpected responses.
- Not testing the error boundary -- TanStack Query's
throwOnError option throws into React error boundaries. Test that error boundaries render correctly.
- Ignoring the isPending vs isFetching distinction --
isPending means no data yet; isFetching means background refetch. Testing only one misses UI bugs.
- Hardcoding staleTime in tests -- set staleTime to 0 in test QueryClient defaults so queries always refetch. Only override staleTime when explicitly testing stale behavior.
- Not testing query cancellation -- when components unmount during a fetch, TanStack Query cancels the request. Test that unmounting does not cause state update warnings.