Open History to see the last commit
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 })),
47)
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 })),
110)
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 })),
131)
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 })),
170)
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 })),
189)
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