Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

testing.md

250 lines8.5 KB

1---
2id: testing
3title: Testing
4---
5​
6Most Angular tests using TanStack Query will involve services or components that call `injectQuery`/`injectMutation`.
7​
8TanStack Query's `inject*` functions integrate with [`PendingTasks`](https://angular.dev/api/core/PendingTasks) which ensures the framework is aware of in-progress queries and mutations.
9​
10This lets the framework, for example during SSR, wait until mutations and queries resolve. In unit tests, `ApplicationRef.whenStable()` and `fixture.whenStable()` work for both Zone.js and Zoneless setups when the work settles right away, such as a synchronous query function or a response flushed through `HttpTestingController`. They can resolve before a query or mutation that takes time settles, so advance fake timers instead, as shown in the sections below.
11​
12> This integration requires Angular 19 or later. Earlier versions of Angular do not support `PendingTasks`.
13​
14## TestBed setup
15​
16Create a fresh `QueryClient` for every spec and provide it with `provideTanStackQuery` or `provideQueryClient`. This keeps caches isolated and lets you change default options per test:
17​
18```ts
19const queryClient = new QueryClient({
20 defaultOptions: {
21 queries: {
22 retry: false, // βœ… faster failure tests
23 },
24 },
25})
26​
27TestBed.configureTestingModule({
28 providers: [provideTanStackQuery(queryClient)],
29})
30```
31​
32> If your applications actual TanStack Query config is used in unit tests, make sure `withDevtools` is not accidentally included in test providers. This can cause slow tests. It is best to keep test and production configs separate.
33​
34If you share helpers, remember to call `queryClient.clear()` (or build a new instance) in `afterEach` so data from one test never bleeds into another.
35​
36## First query test
37​
38Query tests typically run inside `TestBed.runInInjectionContext`, then wait for stability:
39​
40```ts
41const appRef = TestBed.inject(ApplicationRef)
42const query = TestBed.runInInjectionContext(() =>
43 injectQuery(() => ({
44 queryKey: ['greeting'],
45 queryFn: () => 'Hello',
46 })),
48​
49TestBed.tick() // Trigger effect
50​
51// Application is stable when queries are idle
52await appRef.whenStable()
53​
54expect(query.status()).toBe('success')
55expect(query.data()).toBe('Hello')
56```
57​
58Here `whenStable()` resolves after the query settles because the query function returns right away. When using fake timers (Vitest), advance the clock and a microtask before awaiting stability:
59​
60```ts
61await vi.advanceTimersByTimeAsync(0)
62await Promise.resolve()
63await appRef.whenStable()
64```
65​
66## Testing components
67​
68For components, create them through `TestBed.createComponent`. `fixture.whenStable()` can resolve before the query data arrives, so with fake timers, advance the clock past the query function's delay, then run `fixture.detectChanges()` and assert on what the component renders:
69​
70```angular-ts
71beforeEach(() => {
72 vi.useFakeTimers()
73})
74​
75afterEach(() => {
76 vi.useRealTimers()
77})
78​
79it('should render the query data', async () => {
80 @Component({
81 template: `<p>{{ query.data()?.value ?? 'Loading...' }}</p>`,
82 })
83 class ExampleComponent {
84 readonly query = injectQuery(() => ({
85 queryKey: ['example'],
86 queryFn: () =>
87 new Promise<{ value: number }>((resolve) =>
88 setTimeout(() => resolve({ value: 42 }), 10),
89 ),
90 }))
91 }
92​
93 const fixture = TestBed.createComponent(ExampleComponent)
94 fixture.detectChanges()
95 expect(fixture.nativeElement.textContent).toContain('Loading...')
96​
97 await vi.advanceTimersByTimeAsync(11)
98 fixture.detectChanges()
99​
100 expect(fixture.nativeElement.textContent).toContain('42')
101})
102```
103​
104If you use [Angular Testing Library](https://testing-library.com/docs/angular-testing-library/intro/), render the component with `render` and follow the same flow, running change detection through `rendered.fixture`:
105​
106```angular-ts
107it('should render the query data', async () => {
108 @Component({
109 template: `<p>{{ query.data()?.value ?? 'Loading...' }}</p>`,
110 })
111 class ExampleComponent {
112 readonly query = injectQuery(() => ({
113 queryKey: ['example'],
114 queryFn: () =>
115 new Promise<{ value: number }>((resolve) =>
116 setTimeout(() => resolve({ value: 42 }), 10),
117 ),
118 }))
119 }
120​
121 const rendered = await render(ExampleComponent)
122 expect(rendered.getByText('Loading...')).toBeInTheDocument()
123​
124 await vi.advanceTimersByTimeAsync(11)
125 rendered.fixture.detectChanges()
126​
127 expect(rendered.getByText('42')).toBeInTheDocument()
128})
129```
130​
131To test the same query without a component, create it with `TestBed.runInInjectionContext`, advance the clock the same way, and assert on its signals:
132​
133```ts
134it('should resolve the query data', async () => {
135 const query = TestBed.runInInjectionContext(() =>
136 injectQuery(() => ({
137 queryKey: ['example'],
138 queryFn: () =>
139 new Promise<{ value: number }>((resolve) =>
140 setTimeout(() => resolve({ value: 42 }), 10),
141 ),
142 })),
143 )
144 expect(query.isPending()).toBe(true)
145​
146 await vi.advanceTimersByTimeAsync(11)
147​
148 expect(query.data()).toEqual({ value: 42 })
149})
150```
151​
152## Handling retries
153​
154Retries slow failing tests because the default backoff runs three times. Set `retry: false` (or a specific number) through `defaultOptions` or per query to keep tests fast. If a query intentionally retries, assert on the final state rather than intermediate counts.
155​
156## HttpClient & network stubs
157​
158Angular's `HttpClient` testing utilities play nicely with PendingTasks. Register `provideHttpClient()` and `provideHttpClientTesting()` alongside the Query provider and flush responses through `HttpTestingController`:
159​
160```ts
161TestBed.configureTestingModule({
162 providers: [
163 provideHttpClient(),
164 provideHttpClientTesting(),
165 provideTanStackQuery(queryClient),
166 ],
167})
168​
169const httpCtrl = TestBed.inject(HttpTestingController)
170const query = TestBed.runInInjectionContext(() =>
171 injectQuery(() => ({
172 queryKey: ['todos'],
173 queryFn: () => lastValueFrom(TestBed.inject(HttpClient).get('/api/todos')),
174 })),
176​
177const fixturePromise = TestBed.inject(ApplicationRef).whenStable()
178httpCtrl.expectOne('/api/todos').flush([{ id: 1 }])
179await fixturePromise
180​
181expect(query.data()).toEqual([{ id: 1 }])
182httpCtrl.verify()
183```
184​
185## Infinite queries & pagination
186​
187`whenStable()` can resolve before the pages of an infinite query reach the `data()` signal. With fake timers, advance the clock past the query function's delay instead, call `fetchNextPage()`, and advance it again before asserting on `data().pages`. Restore real timers in `afterEach`, so they are restored even when an assertion fails:
188​
189```ts
190beforeEach(() => {
191 vi.useFakeTimers()
192})
193​
194afterEach(() => {
195 vi.useRealTimers()
196})
197​
198it('should load the next page', async () => {
199 const infinite = TestBed.runInInjectionContext(() =>
200 injectInfiniteQuery(() => ({
201 queryKey: ['pages'],
202 queryFn: ({ pageParam }) =>
203 new Promise<string>((resolve) =>
204 setTimeout(() => resolve(`page ${pageParam}`), 10),
205 ),
206 initialPageParam: 1,
207 getNextPageParam: (_lastPage, allPages) => allPages.length + 1,
208 })),
209 )
210​
211 await vi.advanceTimersByTimeAsync(11)
212 expect(infinite.data()?.pages).toEqual(['page 1'])
213​
214 void infinite.fetchNextPage()
215 await vi.advanceTimersByTimeAsync(11)
216 expect(infinite.data()?.pages).toEqual(['page 1', 'page 2'])
217})
218```
219​
220## Mutations and optimistic updates
221​
222`whenStable()` can resolve before a mutation started with `mutate()` settles. With fake timers enabled as in the examples above, advance the clock past the mutation function's delay before asserting on the result:
223​
224```ts
225it('should uppercase the input', async () => {
226 const mutation = TestBed.runInInjectionContext(() =>
227 injectMutation(() => ({
228 mutationFn: (input: string) =>
229 new Promise<string>((resolve) =>
230 setTimeout(() => resolve(input.toUpperCase()), 10),
231 ),
232 })),
233 )
234​
235 mutation.mutate('test')
236 await vi.advanceTimersByTimeAsync(11)
237​
238 expect(mutation.isSuccess()).toBe(true)
239 expect(mutation.data()).toBe('TEST')
240})
241```
242​
243## Quick checklist
244​
245- Fresh `QueryClient` per test (and clear it afterwards)
246- Disable or control retries to avoid timeouts
247- Advance timers + microtasks before `whenStable()` when using fake timers
248- Use `provideHttpClientTesting()` or your preferred mock to assert network calls
249- Advance timers past the query or mutation function after every `refetch`, `fetchNextPage()`, or mutation instead of awaiting `whenStable()`
250- Prefer `TestBed.runInInjectionContext` for service tests, and `TestBed.createComponent` or Angular Testing Library's `render` with `fixture.detectChanges()` for component tests