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

testing.md

213 lines7.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 means tests and SSR can wait until mutations and queries resolve. In unit tests you can use `ApplicationRef.whenStable()` or `fixture.whenStable()` to await query completion. This works for both Zone.js and Zoneless setups.
11​
12> This adapter requires Angular 20.1 or later. It uses `PendingTasks` to keep application stability open while observed work is pending.
13​
14## TestBed setup
15​
16Create a fresh `QueryClient` for every spec and return it from the provider factory. Keeping a reference makes it easy to inspect or clear the cache:
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 application's 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() // Synchronize the test application
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​
58PendingTasks will have `whenStable()` resolve after the query settles. 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, bootstrap them through `TestBed.createComponent`, then await `fixture.whenStable()`:
69​
70```ts
71const fixture = TestBed.createComponent(ExampleComponent)
72fixture.autoDetectChanges()
73​
74await fixture.whenStable()
75expect(fixture.componentInstance.query.data()).toEqual({ value: 42 })
76```
77​
78In zone-based tests, enable `fixture.autoDetectChanges()` so component effects can run again
79as the query settles. Zoneless fixtures enable automatic detection by default.
80​
81When using Angular Testing Library, its `autoDetectChanges` option runs change detection around
82library operations; it does not call `fixture.autoDetectChanges()`. Enable the fixture's automatic
83detection explicitly when awaiting stability in a zone-based component test.
84​
85## Handling retries
86​
87Retries 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.
88​
89## HttpClient & network stubs
90​
91Angular's `provideHttpClientTesting` plays nicely with PendingTasks. Register it after
92`provideHttpClient`, alongside the Query provider, and flush responses through
93`HttpTestingController`:
94​
95```ts
96TestBed.configureTestingModule({
97 providers: [
98 provideHttpClient(),
99 provideHttpClientTesting(),
100 provideTanStackQuery(() => queryClient),
101 ],
102})
103​
104const httpCtrl = TestBed.inject(HttpTestingController)
105const query = TestBed.runInInjectionContext(() =>
106 injectQuery(() => ({
107 queryKey: ['todos'],
108 queryFn: () => lastValueFrom(TestBed.inject(HttpClient).get('/api/todos')),
109 })),
111​
112TestBed.tick() // Synchronize the test application so the request starts
113const fixturePromise = TestBed.inject(ApplicationRef).whenStable()
114httpCtrl.expectOne('/api/todos').flush([{ id: 1 }])
115await fixturePromise
116​
117expect(query.data()).toEqual([{ id: 1 }])
118httpCtrl.verify()
119```
120​
121Mutations can start their HTTP request asynchronously, after their `onMutate` callbacks finish.
122Wait for the request itself before flushing it. This Vitest example uses `vi.waitFor`:
123​
124```ts
125const http = TestBed.inject(HttpClient)
126const mutation = TestBed.runInInjectionContext(() =>
127 injectMutation(() => ({
128 mutationFn: (input: { email: string }) =>
129 lastValueFrom(http.post('/api/reset', input)),
130 })),
132​
133TestBed.tick()
134mutation.mutate({ email: 'person@example.com' })
135​
136const request = await vi.waitFor(() => httpCtrl.expectOne('/api/reset'))
137request.flush({ ok: true })
138await TestBed.inject(ApplicationRef).whenStable()
139​
140expect(mutation.isSuccess()).toBe(true)
141httpCtrl.verify()
142```
143​
144Do not await stability before flushing a request controlled by the test: the unanswered request
145keeps the query or mutation stuck on pending.
146​
147Test observable results after normal Angular initialization and updates. For components, render
148with `fixture.autoDetectChanges()` and await `fixture.whenStable()` when the operation should finish.
149For injection-context-only tests, synchronize the test application as shown above. When using
150HTTP mocks or fake timers, flush the request or advance time before awaiting stability.
151​
152Avoid asserting an exact subscription order or a stale intermediate value during initialization.
153Those are implementation details. To test pending mutation or fetching state, hold the operation
154open with a controlled promise and assert after rendering; do not await stability until you
155resolve that promise. To test completed state, resolve the operation and await stability before
156asserting the result.
157​
158## Infinite queries & pagination
159​
160Use the same pattern for infinite queries: call `fetchNextPage()`, advance timers if you are faking time, then await stability and assert on `data().pages`.
161​
162```ts
163const infinite = TestBed.runInInjectionContext(() =>
164 injectInfiniteQuery(() => ({
165 queryKey: ['pages'],
166 initialPageParam: 1,
167 queryFn: ({ pageParam }) => fetchPage(pageParam),
168 getNextPageParam: (last, all) => all.length + 1,
169 })),
171​
172TestBed.tick()
173await appRef.whenStable()
174expect(infinite.data()?.pages).toHaveLength(1)
175​
176await infinite.fetchNextPage()
177await appRef.whenStable()
178​
179expect(infinite.data()?.pages).toHaveLength(2)
180```
181​
182## Mutations and optimistic updates
183​
184```ts
185const mutation = TestBed.runInInjectionContext(() =>
186 injectMutation(() => ({
187 mutationFn: async (input: string) => input.toUpperCase(),
188 })),
190​
191mutation.mutate('test')
192​
193// Synchronize the test application
194TestBed.tick()
195​
196await appRef.whenStable()
197​
198expect(mutation.isSuccess()).toBe(true)
199expect(mutation.data()).toBe('TEST')
200```
201​
202`whenStable()` waits for every mutation invocation, including awaited lifecycle callbacks.
203Resolve or reject all outstanding mocked mutations before awaiting stability; calling `reset()`
204does not finish a request. Queries paused offline also keep stability open until resumed or cancelled.
205​
206## Quick checklist
207​
208- Fresh `QueryClient` per test (and clear it afterwards)
209- Disable or control retries to avoid timeouts
210- Advance timers + microtasks before `whenStable()` when using fake timers
211- Use `provideHttpClientTesting` or your preferred mock to assert network calls
212- Resolve controlled requests, then await `whenStable()` for settled-state assertions
213- Prefer `TestBed.runInInjectionContext` for service tests and `fixture.whenStable()` for component tests