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