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

pending-tasks.test.ts

624 lines18.8 KB

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 { queryKey, 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 = queryKey()
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 = queryKey()
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()).toEqual(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()).toEqual(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 = queryKey()
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 = queryKey()
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 = queryKey()
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.toEqual(undefined)
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.toEqual(undefined)
318 })
319 })
320​
321 describe('Concurrent Operations', () => {
322 it('should handle multiple queries running simultaneously', async () => {
323 const key1 = queryKey()
324 const key2 = queryKey()
325 const key3 = queryKey()
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 = queryKey()
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 = queryKey()
458 const key2 = queryKey()
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()).toEqual({ id: 1 })
490 expect(query2.status()).toBe('success')
491 expect(query2.data()).toEqual({ 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 = queryKey()
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 = queryKey()
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 = queryKey()
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 = queryKey()
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})