Open History to see the last commit
1import {
2 ApplicationRef,
3 Component,
4 provideZonelessChangeDetection,
5} from '@angular/core'
6import { TestBed } from '@angular/core/testing'
7import { HttpClient, provideHttpClient } from '@angular/common/http'
8import {
9 HttpTestingController,
10 provideHttpClientTesting,
11} from '@angular/common/http/testing'
12import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
13import { createKey, sleep } from '@tanstack/query-test-utils'
14import { lastValueFrom } from 'rxjs'
15import {
16 QueryClient,
17 injectMutation,
18 injectQuery,
19 onlineManager,
20 provideTanStackQuery,
21} from '..'
22β
23describe('PendingTasks Integration', () => {
24 let queryClient: QueryClient
25β
26 beforeEach(() => {
27 vi.useFakeTimers()
28β
29 queryClient = new QueryClient({
30 defaultOptions: {
31 queries: {
32 retry: false,
33 },
34 mutations: {
35 retry: false,
36 },
37 },
38 })
39β
40 TestBed.configureTestingModule({
41 providers: [
42 provideZonelessChangeDetection(),
43 provideTanStackQuery(queryClient),
44 ],
45 })
46 })
47β
48 afterEach(() => {
49 onlineManager.setOnline(true)
50 queryClient.clear()
51 vi.useRealTimers()
52 })
53β
54 describe('Synchronous Resolution', () => {
55 it('should handle synchronous queryFn with whenStable()', async () => {
56 const app = TestBed.inject(ApplicationRef)
57β
58 const key = createKey()
59 const query = TestBed.runInInjectionContext(() =>
60 injectQuery(() => ({
61 queryKey: key,
62 queryFn: () => 'instant-data', // Resolves synchronously
63 })),
64 )
65β
66 // Should start as pending even with synchronous data
67 expect(query.status()).toBe('pending')
68 expect(query.data()).toBeUndefined()
69β
70 const stablePromise = app.whenStable()
71 // Flush microtasks to allow TanStack Query's scheduled notifications to process
72 await Promise.resolve()
73 await vi.advanceTimersByTimeAsync(10)
74 await stablePromise
75β
76 // Should work correctly even though queryFn was synchronous
77 expect(query.status()).toBe('success')
78 expect(query.data()).toBe('instant-data')
79 })
80β
81 it('should handle synchronous error with whenStable()', async () => {
82 const app = TestBed.inject(ApplicationRef)
83β
84 const key = createKey()
85 const query = TestBed.runInInjectionContext(() =>
86 injectQuery(() => ({
87 queryKey: key,
88 queryFn: () => {
89 throw new Error('instant-error')
90 }, // Throws synchronously
91 })),
92 )
93β
94 const stablePromise = app.whenStable()
95 // Flush microtasks to allow TanStack Query's scheduled notifications to process
96 await Promise.resolve()
97 await vi.advanceTimersByTimeAsync(10)
98 await stablePromise
99 expect(query.status()).toBe('error')
100 expect(query.error()).toStrictEqual(new Error('instant-error'))
101 })
102β
103 it('should handle synchronous mutationFn with whenStable()', async () => {
104 const app = TestBed.inject(ApplicationRef)
105 let mutationFnCalled = false
106β
107 const mutation = TestBed.runInInjectionContext(() =>
108 injectMutation(() => ({
109 mutationFn: async (data: string) => {
110 mutationFnCalled = true
111 await Promise.resolve()
112 return `processed: ${data}`
113 },
114 })),
115 )
116β
117 mutation.mutate('test')
118 TestBed.tick()
119β
120 const stablePromise = app.whenStable()
121 await Promise.resolve()
122 await vi.advanceTimersByTimeAsync(10)
123 await stablePromise
124 expect(mutationFnCalled).toBe(true)
125 expect(mutation.isSuccess()).toBe(true)
126 expect(mutation.data()).toBe('processed: test')
127 })
128β
129 it('should handle synchronous mutation error with whenStable()', async () => {
130 const app = TestBed.inject(ApplicationRef)
131β
132 const mutation = TestBed.runInInjectionContext(() =>
133 injectMutation(() => ({
134 mutationFn: async () => {
135 await Promise.resolve()
136 throw new Error('sync-mutation-error')
137 },
138 })),
139 )
140β
141 mutation.mutate()
142 TestBed.tick()
143β
144 const stablePromise = app.whenStable()
145 await Promise.resolve()
146 await vi.advanceTimersByTimeAsync(10)
147 await stablePromise
148 expect(mutation.isError()).toBe(true)
149 expect(mutation.error()).toStrictEqual(new Error('sync-mutation-error'))
150 })
151 })
152β
153 describe('Race Conditions', () => {
154 it('should handle query that completes during initial subscription', async () => {
155 const key = createKey()
156 const app = TestBed.inject(ApplicationRef)
157 let resolveQuery: (value: string) => void
158β
159 const queryPromise = new Promise<string>((resolve) => {
160 resolveQuery = resolve
161 })
162β
163 const query = TestBed.runInInjectionContext(() =>
164 injectQuery(() => ({
165 queryKey: key,
166 queryFn: () => queryPromise,
167 })),
168 )
169β
170 // Resolve immediately to create potential race condition
171 resolveQuery!('race-data')
172β
173 const stablePromise = app.whenStable()
174 await Promise.resolve()
175 await vi.advanceTimersByTimeAsync(10)
176 await stablePromise
177 expect(query.status()).toBe('success')
178 expect(query.data()).toBe('race-data')
179 })
180β
181 it('should handle rapid refetches without task leaks', async () => {
182 const app = TestBed.inject(ApplicationRef)
183 let callCount = 0
184β
185 const key = createKey()
186 const query = TestBed.runInInjectionContext(() =>
187 injectQuery(() => ({
188 queryKey: key,
189 queryFn: async () => {
190 callCount++
191 await sleep(10)
192 return `data-${callCount}`
193 },
194 })),
195 )
196β
197 // Trigger multiple rapid refetches
198 query.refetch()
199 query.refetch()
200 query.refetch()
201β
202 const stablePromise = app.whenStable()
203 await vi.advanceTimersByTimeAsync(20)
204 await stablePromise
205 expect(query.status()).toBe('success')
206 expect(query.data()).toMatch(/^data-\d+$/)
207 })
208β
209 it('should keep PendingTasks active while query retry is paused offline', async () => {
210 const app = TestBed.inject(ApplicationRef)
211 let attempt = 0
212β
213 const key = createKey()
214 const query = TestBed.runInInjectionContext(() =>
215 injectQuery(() => ({
216 queryKey: key,
217 retry: 1,
218 retryDelay: 50, // Longer delay to ensure we can go offline before retry
219 queryFn: async () => {
220 attempt++
221 if (attempt === 1) {
222 throw new Error('offline-fail')
223 }
224 await sleep(10)
225 return 'final-data'
226 },
227 })),
228 )
229β
230 // Allow the initial attempt to start and fail
231 await vi.advanceTimersByTimeAsync(0)
232 await Promise.resolve()
233β
234 // Wait for the first attempt to complete and start retry delay
235 await vi.advanceTimersByTimeAsync(10)
236 await Promise.resolve()
237 expect(query.status()).toBe('pending')
238 expect(query.fetchStatus()).toBe('fetching')
239β
240 // Simulate the app going offline during retry delay
241 onlineManager.setOnline(false)
242β
243 // Advance past the retry delay to trigger the pause
244 await vi.advanceTimersByTimeAsync(50)
245 await Promise.resolve()
246 expect(query.fetchStatus()).toBe('paused')
247β
248 const stablePromise = app.whenStable()
249 let stableResolved = false
250 void stablePromise.then(() => {
251 stableResolved = true
252 })
253β
254 await Promise.resolve()
255β
256 // PendingTasks should continue blocking stability while the fetch is paused
257 expect(stableResolved).toBe(false)
258 expect(query.status()).toBe('pending')
259β
260 // Bring the app back online so the retry can continue
261 onlineManager.setOnline(true)
262β
263 // Give time for the retry to resume and complete
264 await vi.advanceTimersByTimeAsync(20)
265 await Promise.resolve()
266 await stablePromise
267 expect(stableResolved).toBe(true)
268 expect(query.status()).toBe('success')
269 expect(query.data()).toBe('final-data')
270 })
271 })
272β
273 describe('Component Destruction', () => {
274 @Component({
275 template: '',
276 })
277 class TestComponent {
278 query = injectQuery(() => ({
279 queryKey: ['component-query'],
280 queryFn: () => sleep(100).then(() => 'component-data'),
281 }))
282β
283 mutation = injectMutation(() => ({
284 mutationFn: (data: string) =>
285 sleep(100).then(() => `processed: ${data}`),
286 }))
287 }
288β
289 it('should cleanup pending tasks when component with active query is destroyed', async () => {
290 const app = TestBed.inject(ApplicationRef)
291 const fixture = TestBed.createComponent(TestComponent)
292β
293 // Start the query
294 expect(fixture.componentInstance.query.status()).toBe('pending')
295β
296 // Destroy component while query is running
297 fixture.destroy()
298β
299 // Angular should become stable even though component was destroyed
300 const stablePromise = app.whenStable()
301 await vi.advanceTimersByTimeAsync(150)
302 await expect(stablePromise).resolves.toBeUndefined()
303 })
304β
305 it('should cleanup pending tasks when component with active mutation is destroyed', async () => {
306 const app = TestBed.inject(ApplicationRef)
307 const fixture = TestBed.createComponent(TestComponent)
308β
309 fixture.componentInstance.mutation.mutate('test')
310β
311 // Destroy component while mutation is running
312 fixture.destroy()
313β
314 // Angular should become stable even though component was destroyed
315 const stablePromise = app.whenStable()
316 await vi.advanceTimersByTimeAsync(150)
317 await expect(stablePromise).resolves.toBeUndefined()
318 })
319 })
320β
321 describe('Concurrent Operations', () => {
322 it('should handle multiple queries running simultaneously', async () => {
323 const key1 = createKey()
324 const key2 = createKey()
325 const key3 = createKey()
326 const app = TestBed.inject(ApplicationRef)
327β
328 const query1 = TestBed.runInInjectionContext(() =>
329 injectQuery(() => ({
330 queryKey: key1,
331 queryFn: () => sleep(30).then(() => 'data-1'),
332 })),
333 )
334β
335 const query2 = TestBed.runInInjectionContext(() =>
336 injectQuery(() => ({
337 queryKey: key2,
338 queryFn: () => sleep(50).then(() => 'data-2'),
339 })),
340 )
341β
342 const query3 = TestBed.runInInjectionContext(() =>
343 injectQuery(() => ({
344 queryKey: key3,
345 queryFn: () => 'instant-data', // Synchronous
346 })),
347 )
348β
349 // All queries should start
350 expect(query1.status()).toBe('pending')
351 expect(query2.status()).toBe('pending')
352 expect(query3.status()).toBe('pending')
353β
354 const stablePromise = app.whenStable()
355 await vi.advanceTimersByTimeAsync(60)
356 await stablePromise
357β
358 // All queries should be complete
359 expect(query1.status()).toBe('success')
360 expect(query1.data()).toBe('data-1')
361 expect(query2.status()).toBe('success')
362 expect(query2.data()).toBe('data-2')
363 expect(query3.status()).toBe('success')
364 expect(query3.data()).toBe('instant-data')
365 })
366β
367 it('should handle multiple mutations running simultaneously', async () => {
368 const app = TestBed.inject(ApplicationRef)
369β
370 const mutation1 = TestBed.runInInjectionContext(() =>
371 injectMutation(() => ({
372 mutationFn: (data: string) =>
373 sleep(30).then(() => `processed-1: ${data}`),
374 })),
375 )
376β
377 const mutation2 = TestBed.runInInjectionContext(() =>
378 injectMutation(() => ({
379 mutationFn: (data: string) =>
380 sleep(50).then(() => `processed-2: ${data}`),
381 })),
382 )
383β
384 const mutation3 = TestBed.runInInjectionContext(() =>
385 injectMutation(() => ({
386 mutationFn: async (data: string) => {
387 await Promise.resolve()
388 return `processed-3: ${data}`
389 },
390 })),
391 )
392β
393 // Start all mutations
394 mutation1.mutate('test1')
395 mutation2.mutate('test2')
396 mutation3.mutate('test3')
397 TestBed.tick()
398β
399 const stablePromise = app.whenStable()
400 await vi.advanceTimersByTimeAsync(60)
401 await stablePromise
402β
403 // All mutations should be complete
404 expect(mutation1.isSuccess()).toBe(true)
405 expect(mutation1.data()).toBe('processed-1: test1')
406 expect(mutation2.isSuccess()).toBe(true)
407 expect(mutation2.data()).toBe('processed-2: test2')
408 expect(mutation3.isSuccess()).toBe(true)
409 expect(mutation3.data()).toBe('processed-3: test3')
410 })
411β
412 it('should handle mixed queries and mutations', async () => {
413 const app = TestBed.inject(ApplicationRef)
414β
415 const key = createKey()
416 const query = TestBed.runInInjectionContext(() =>
417 injectQuery(() => ({
418 queryKey: key,
419 queryFn: () => sleep(40).then(() => 'query-data'),
420 })),
421 )
422β
423 const mutation = TestBed.runInInjectionContext(() =>
424 injectMutation(() => ({
425 mutationFn: (data: string) =>
426 sleep(60).then(() => `mutation: ${data}`),
427 })),
428 )
429β
430 // Start both operations
431 mutation.mutate('test')
432β
433 const stablePromise = app.whenStable()
434 await vi.advanceTimersByTimeAsync(70)
435 await stablePromise
436β
437 // Both should be complete
438 expect(query.status()).toBe('success')
439 expect(query.data()).toBe('query-data')
440 expect(mutation.isSuccess()).toBe(true)
441 expect(mutation.data()).toBe('mutation: test')
442 })
443 })
444β
445 describe('HttpClient Integration', () => {
446 beforeEach(() => {
447 TestBed.configureTestingModule({
448 providers: [provideHttpClient(), provideHttpClientTesting()],
449 })
450 })
451β
452 it('should handle multiple HttpClient requests with lastValueFrom', async () => {
453 const app = TestBed.inject(ApplicationRef)
454 const httpClient = TestBed.inject(HttpClient)
455 const httpTestingController = TestBed.inject(HttpTestingController)
456β
457 const key1 = createKey()
458 const key2 = createKey()
459β
460 const query1 = TestBed.runInInjectionContext(() =>
461 injectQuery(() => ({
462 queryKey: key1,
463 queryFn: () =>
464 lastValueFrom(httpClient.get<{ id: number }>('/api/1')),
465 })),
466 )
467β
468 const query2 = TestBed.runInInjectionContext(() =>
469 injectQuery(() => ({
470 queryKey: key2,
471 queryFn: () =>
472 lastValueFrom(httpClient.get<{ id: number }>('/api/2')),
473 })),
474 )
475β
476 // Schedule HTTP responses
477 setTimeout(() => {
478 const req1 = httpTestingController.expectOne('/api/1')
479 req1.flush({ id: 1 })
480β
481 const req2 = httpTestingController.expectOne('/api/2')
482 req2.flush({ id: 2 })
483 }, 10)
484β
485 const stablePromise = app.whenStable()
486 await vi.advanceTimersByTimeAsync(20)
487 await stablePromise
488 expect(query1.status()).toBe('success')
489 expect(query1.data()).toStrictEqual({ id: 1 })
490 expect(query2.status()).toBe('success')
491 expect(query2.data()).toStrictEqual({ id: 2 })
492β
493 httpTestingController.verify()
494 })
495β
496 it('should handle HttpClient request cancellation', async () => {
497 const app = TestBed.inject(ApplicationRef)
498 const httpClient = TestBed.inject(HttpClient)
499 const httpTestingController = TestBed.inject(HttpTestingController)
500β
501 const key = createKey()
502 const query = TestBed.runInInjectionContext(() =>
503 injectQuery(() => ({
504 queryKey: key,
505 queryFn: () =>
506 lastValueFrom(httpClient.get<{ data: string }>('/api/cancel')),
507 })),
508 )
509β
510 // Cancel the request before it completes
511 setTimeout(() => {
512 const req = httpTestingController.expectOne('/api/cancel')
513 req.error(new ProgressEvent('error'), {
514 status: 0,
515 statusText: 'Unknown Error',
516 })
517 }, 10)
518β
519 const stablePromise = app.whenStable()
520 await vi.advanceTimersByTimeAsync(20)
521 await stablePromise
522 expect(query.status()).toBe('error')
523β
524 httpTestingController.verify()
525 })
526 })
527β
528 describe('Edge Cases', () => {
529 it('should handle query cancellation mid-flight', async () => {
530 const key = createKey()
531 const app = TestBed.inject(ApplicationRef)
532β
533 const query = TestBed.runInInjectionContext(() =>
534 injectQuery(() => ({
535 queryKey: key,
536 queryFn: () => sleep(100).then(() => 'data'),
537 })),
538 )
539β
540 // Cancel the query after a short delay
541 setTimeout(() => {
542 queryClient.cancelQueries({ queryKey: key })
543 }, 20)
544β
545 // Advance to the cancellation point
546 await vi.advanceTimersByTimeAsync(20)
547 TestBed.tick()
548β
549 const stablePromise = app.whenStable()
550 await vi.advanceTimersByTimeAsync(130)
551 await stablePromise
552β
553 // Cancellation should restore the pre-fetch state
554 expect(query.status()).toBe('pending')
555 expect(query.fetchStatus()).toBe('idle')
556 })
557β
558 it('should handle query retry and pending task tracking', async () => {
559 const app = TestBed.inject(ApplicationRef)
560 let attemptCount = 0
561β
562 const key = createKey()
563 const query = TestBed.runInInjectionContext(() =>
564 injectQuery(() => ({
565 queryKey: key,
566 retry: 2,
567 retryDelay: 10,
568 queryFn: async () => {
569 attemptCount++
570 if (attemptCount <= 2) {
571 throw new Error(`Attempt ${attemptCount} failed`)
572 }
573 return 'success-data'
574 },
575 })),
576 )
577β
578 const stablePromise = app.whenStable()
579 await vi.advanceTimersByTimeAsync(50)
580 await stablePromise
581 expect(query.status()).toBe('success')
582 expect(query.data()).toBe('success-data')
583 expect(attemptCount).toBe(3) // Initial + 2 retries
584 })
585β
586 it('should handle mutation with optimistic updates', async () => {
587 const app = TestBed.inject(ApplicationRef)
588 const testQueryKey = createKey()
589β
590 queryClient.setQueryData(testQueryKey, 'initial-data')
591β
592 const mutation = TestBed.runInInjectionContext(() =>
593 injectMutation(() => ({
594 mutationFn: (newData: string) => sleep(50).then(() => newData),
595 onMutate: async (newData) => {
596 // Optimistic update
597 const previousData = queryClient.getQueryData(testQueryKey)
598 queryClient.setQueryData(testQueryKey, newData)
599 return { previousData }
600 },
601 onError: (_err, _newData, context) => {
602 // Rollback on error
603 if (context?.previousData) {
604 queryClient.setQueryData(testQueryKey, context.previousData)
605 }
606 },
607 })),
608 )
609β
610 mutation.mutate('optimistic-data')
611 await Promise.resolve()
612β
613 // Data should be optimistically updated immediately
614 expect(queryClient.getQueryData(testQueryKey)).toBe('optimistic-data')
615β
616 const stablePromise = app.whenStable()
617 await vi.advanceTimersByTimeAsync(60)
618 await stablePromise
619 expect(mutation.isSuccess()).toBe(true)
620 expect(mutation.data()).toBe('optimistic-data')
621 expect(queryClient.getQueryData(testQueryKey)).toBe('optimistic-data')
622 })
623 })
624})