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