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

pending-tasks.test.ts

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