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

pending-tasks.test.ts

784 lines22.8 KB

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