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