Open History to see the last commit
1import {
2 ApplicationRef,
3 ChangeDetectionStrategy,
4 Component,
5 Injector,
6 NgZone,
7 computed,
8 effect,
9 input,
10 provideZonelessChangeDetection,
11 signal,
12} from '@angular/core'
13import { TestBed } from '@angular/core/testing'
14import { HttpClient, provideHttpClient } from '@angular/common/http'
15import {
16 HttpTestingController,
17 provideHttpClientTesting,
18} from '@angular/common/http/testing'
19import {
20 afterEach,
21 beforeEach,
22 describe,
23 expect,
24 expectTypeOf,
25 test,
26 vi,
27} from 'vitest'
28import { queryKey, sleep } from '@tanstack/query-test-utils'
29import { lastValueFrom } from 'rxjs'
30import {
31 QueryCache,
32 QueryClient,
33 injectQuery,
34 provideIsRestoring,
35 provideTanStackQuery,
36} from '..'
37import { registerSignalInput } from './test-utils'
38import type { CreateQueryOptions, OmitKeyof, QueryFunction } from '..'
39
40describe('injectQuery', () => {
41 let queryCache: QueryCache
42 let queryClient: QueryClient
43 beforeEach(() => {
44 vi.useFakeTimers()
45 queryCache = new QueryCache()
46 queryClient = new QueryClient({ queryCache })
47 TestBed.configureTestingModule({
48 providers: [
49 provideZonelessChangeDetection(),
50 provideTanStackQuery(queryClient),
51 ],
52 })
53 })
54
55 afterEach(() => {
56 vi.useRealTimers()
57 })
58
59 test('should return the correct types', () => {
60 const key = queryKey()
61
62 @Component({
63 selector: 'app-test',
64 template: '',
65 changeDetection: ChangeDetectionStrategy.OnPush,
66 })
67 class TestComponent {
68 // unspecified query function should default to unknown
69 noQueryFn = injectQuery(() => ({
70 queryKey: key,
71 }))
72
73 // it should infer the result type from the query function
74 fromQueryFn = injectQuery(() => ({
75 queryKey: key,
76 queryFn: () => 'test',
77 }))
78
79 // it should be possible to specify the result type
80 withResult = injectQuery<string>(() => ({
81 queryKey: key,
82 queryFn: () => 'test',
83 }))
84
85 // it should be possible to specify the error type
86 withError = injectQuery<string, { message: string }>(() => ({
87 queryKey: key,
88 queryFn: () => 'test',
89 }))
90
91 // it should infer the result type from the configuration
92 withResultInfer = injectQuery(() => ({
93 queryKey: key,
94 queryFn: () => true,
95 }))
96
97 // it should be possible to specify a union type as result type
98 unionTypeSync = injectQuery(() => ({
99 queryKey: key,
100 queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
101 }))
102
103 unionTypeAsync = injectQuery<'a' | 'b'>(() => ({
104 queryKey: key,
105 queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
106 }))
107
108 // it should infer the result type from a generic query function
109 fromGenericQueryFn = (() => {
110 function queryFn<T = string>(): Promise<T> {
111 return Promise.resolve({} as T)
112 }
113 return injectQuery(() => ({
114 queryKey: key,
115 queryFn: () => queryFn(),
116 }))
117 })()
118
119 // todo use query options?
120 fromGenericOptionsQueryFn = (() => {
121 function queryFn<T = string>(): Promise<T> {
122 return Promise.resolve({} as T)
123 }
124 return injectQuery(() => ({
125 queryKey: key,
126 queryFn: () => queryFn(),
127 }))
128 })()
129
130 fromMyDataArrayKeyQueryFn = (() => {
131 type MyData = number
132 type MyQueryKey = readonly ['my-data', number]
133 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
134 queryKey: [, n],
135 }) => {
136 return n + 42
137 }
138 return injectQuery(() => ({
139 queryKey: ['my-data', 100] as const,
140 queryFn: getMyDataArrayKey,
141 }))
142 })()
143
144 // it should handle query-functions that return Promise<any>
145 fromPromiseAnyQueryFn = injectQuery(() => ({
146 queryKey: key,
147 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
148 }))
149
150 fromGetMyDataStringKeyQueryFn = (() => {
151 type MyData = number
152 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
153 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
154 return Number(context.queryKey[0]) + 42
155 }
156 return injectQuery(() => ({
157 queryKey: ['1'] as ['1'],
158 queryFn: getMyDataStringKey,
159 }))
160 })()
161
162 // Wrapped queries
163 fromWrappedQuery = (() => {
164 const createWrappedQuery = <
165 TQueryKey extends [string, Record<string, unknown>?],
166 TQueryFnData,
167 TError,
168 TData = TQueryFnData,
169 >(
170 qk: TQueryKey,
171 fetcher: (obj: TQueryKey[1], token: string) => Promise<TQueryFnData>,
172 options?: OmitKeyof<
173 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
174 'queryKey' | 'queryFn' | 'initialData',
175 'safely'
176 >,
177 ) =>
178 injectQuery(() => ({
179 queryKey: qk,
180 queryFn: () => fetcher(qk[1], 'token'),
181 ...options,
182 }))
183 return createWrappedQuery([''], () => Promise.resolve('1'))
184 })()
185
186 fromWrappedFuncStyleQuery = (() => {
187 const createWrappedFuncStyleQuery = <
188 TQueryKey extends [string, Record<string, unknown>?],
189 TQueryFnData,
190 TError,
191 TData = TQueryFnData,
192 >(
193 qk: TQueryKey,
194 fetcher: () => Promise<TQueryFnData>,
195 options?: OmitKeyof<
196 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
197 'queryKey' | 'queryFn' | 'initialData',
198 'safely'
199 >,
200 ) => injectQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
201 return createWrappedFuncStyleQuery([''], () => Promise.resolve(true))
202 })()
203 }
204
205 const fixture = TestBed.createComponent(TestComponent)
206 fixture.detectChanges()
207 const {
208 noQueryFn,
209 fromQueryFn,
210 withResult,
211 withError,
212 withResultInfer,
213 unionTypeSync,
214 unionTypeAsync,
215 fromGenericQueryFn,
216 fromGenericOptionsQueryFn,
217 fromMyDataArrayKeyQueryFn,
218 fromPromiseAnyQueryFn,
219 fromGetMyDataStringKeyQueryFn,
220 fromWrappedQuery,
221 fromWrappedFuncStyleQuery,
222 } = fixture.componentInstance
223
224 expectTypeOf(noQueryFn.data()).toEqualTypeOf<unknown>()
225 expectTypeOf(noQueryFn.error()).toEqualTypeOf<Error | null>()
226
227 expectTypeOf(fromQueryFn.data()).toEqualTypeOf<string | undefined>()
228 expectTypeOf(fromQueryFn.error()).toEqualTypeOf<Error | null>()
229
230 expectTypeOf(withResult.data()).toEqualTypeOf<string | undefined>()
231 expectTypeOf(withResult.error()).toEqualTypeOf<Error | null>()
232
233 expectTypeOf(withError.data()).toEqualTypeOf<string | undefined>()
234 expectTypeOf(withError.error()).toEqualTypeOf<{ message: string } | null>()
235
236 expectTypeOf(withResultInfer.data()).toEqualTypeOf<boolean | undefined>()
237 expectTypeOf(withResultInfer.error()).toEqualTypeOf<Error | null>()
238
239 expectTypeOf(unionTypeSync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
240 expectTypeOf(unionTypeAsync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
241
242 expectTypeOf(fromGenericQueryFn.data()).toEqualTypeOf<string | undefined>()
243 expectTypeOf(fromGenericQueryFn.error()).toEqualTypeOf<Error | null>()
244
245 expectTypeOf(fromGenericOptionsQueryFn.data()).toEqualTypeOf<
246 string | undefined
247 >()
248 expectTypeOf(
249 fromGenericOptionsQueryFn.error(),
250 ).toEqualTypeOf<Error | null>()
251
252 expectTypeOf(fromMyDataArrayKeyQueryFn.data()).toEqualTypeOf<
253 number | undefined
254 >()
255
256 expectTypeOf(fromPromiseAnyQueryFn.data()).toEqualTypeOf<any | undefined>()
257 expectTypeOf(fromGetMyDataStringKeyQueryFn.data()).toEqualTypeOf<
258 number | undefined
259 >()
260 expectTypeOf(fromWrappedQuery.data()).toEqualTypeOf<string | undefined>()
261 expectTypeOf(fromWrappedFuncStyleQuery.data()).toEqualTypeOf<
262 boolean | undefined
263 >()
264 })
265
266 test('should return pending status initially', () => {
267 @Component({
268 selector: 'app-test',
269 template: '',
270 changeDetection: ChangeDetectionStrategy.OnPush,
271 })
272 class TestComponent {
273 query = injectQuery(() => ({
274 queryKey: ['key1'],
275 queryFn: () => sleep(10).then(() => 'Some data'),
276 }))
277 }
278
279 const fixture = TestBed.createComponent(TestComponent)
280 fixture.detectChanges()
281 const query = fixture.componentInstance.query
282
283 expect(query.status()).toBe('pending')
284 expect(query.isPending()).toBe(true)
285 expect(query.isFetching()).toBe(true)
286 expect(query.isStale()).toBe(true)
287 expect(query.isFetched()).toBe(false)
288 })
289
290 test('should resolve to success and update signal: injectQuery()', async () => {
291 @Component({
292 selector: 'app-test',
293 template: '',
294 changeDetection: ChangeDetectionStrategy.OnPush,
295 })
296 class TestComponent {
297 query = injectQuery(() => ({
298 queryKey: ['key2'],
299 queryFn: () => sleep(10).then(() => 'result2'),
300 }))
301 }
302
303 const fixture = TestBed.createComponent(TestComponent)
304 fixture.detectChanges()
305 const query = fixture.componentInstance.query
306
307 await vi.advanceTimersByTimeAsync(11)
308 expect(query.status()).toBe('success')
309 expect(query.data()).toBe('result2')
310 expect(query.isPending()).toBe(false)
311 expect(query.isFetching()).toBe(false)
312 expect(query.isFetched()).toBe(true)
313 expect(query.isSuccess()).toBe(true)
314 })
315
316 test('should reject and update signal', async () => {
317 @Component({
318 selector: 'app-test',
319 template: '',
320 changeDetection: ChangeDetectionStrategy.OnPush,
321 })
322 class TestComponent {
323 query = injectQuery(() => ({
324 retry: false,
325 queryKey: ['key3'],
326 queryFn: () =>
327 sleep(10).then(() => Promise.reject(new Error('Some error'))),
328 }))
329 }
330
331 const fixture = TestBed.createComponent(TestComponent)
332 fixture.detectChanges()
333 const query = fixture.componentInstance.query
334
335 await vi.advanceTimersByTimeAsync(11)
336 expect(query.status()).toBe('error')
337 expect(query.data()).toBe(undefined)
338 expect(query.error()).toMatchObject({ message: 'Some error' })
339 expect(query.isPending()).toBe(false)
340 expect(query.isFetching()).toBe(false)
341 expect(query.isError()).toBe(true)
342 expect(query.failureCount()).toBe(1)
343 expect(query.failureReason()).toMatchObject({ message: 'Some error' })
344 })
345
346 test('should update query on options contained signal change', async () => {
347 const key = signal(['key6', 'key7'])
348 const spy = vi.fn(() => sleep(10).then(() => 'Some data'))
349
350 @Component({
351 selector: 'app-test',
352 template: '',
353 changeDetection: ChangeDetectionStrategy.OnPush,
354 })
355 class TestComponent {
356 key = key
357 spy = spy
358 query = injectQuery(() => ({
359 queryKey: this.key(),
360 queryFn: this.spy,
361 }))
362 }
363
364 const fixture = TestBed.createComponent(TestComponent)
365 fixture.detectChanges()
366 const query = fixture.componentInstance.query
367
368 await vi.advanceTimersByTimeAsync(0)
369 expect(spy).toHaveBeenCalledTimes(1)
370
371 await vi.advanceTimersByTimeAsync(11)
372 expect(query.status()).toBe('success')
373
374 key.set(['key8'])
375 fixture.detectChanges()
376
377 expect(spy).toHaveBeenCalledTimes(2)
378 // should call queryFn with context containing the new queryKey
379 expect(spy).toBeCalledWith({
380 client: queryClient,
381 meta: undefined,
382 queryKey: ['key8'],
383 signal: expect.anything(),
384 })
385 })
386
387 test('should only run query once enabled signal is set to true', async () => {
388 const spy = vi.fn(() => sleep(10).then(() => 'Some data'))
389 const enabled = signal(false)
390
391 @Component({
392 selector: 'app-test',
393 template: '',
394 changeDetection: ChangeDetectionStrategy.OnPush,
395 })
396 class TestComponent {
397 enabled = enabled
398 spy = spy
399 query = injectQuery(() => ({
400 queryKey: ['key9'],
401 queryFn: this.spy,
402 enabled: this.enabled(),
403 }))
404 }
405
406 const fixture = TestBed.createComponent(TestComponent)
407 fixture.detectChanges()
408 const query = fixture.componentInstance.query
409
410 expect(spy).not.toHaveBeenCalled()
411 expect(query.status()).toBe('pending')
412
413 enabled.set(true)
414
415 await vi.advanceTimersByTimeAsync(11)
416 expect(spy).toHaveBeenCalledTimes(1)
417 expect(query.status()).toBe('success')
418 })
419
420 test('should properly execute dependant queries', async () => {
421 const dependentQueryFn = vi
422 .fn()
423 .mockImplementation(() => sleep(1000).then(() => 'Some data'))
424
425 @Component({
426 selector: 'app-test',
427 template: '',
428 changeDetection: ChangeDetectionStrategy.OnPush,
429 })
430 class TestComponent {
431 query1 = injectQuery(() => ({
432 queryKey: ['dependant1'],
433 queryFn: () => sleep(10).then(() => 'Some data'),
434 }))
435
436 query2 = injectQuery(
437 computed(() => ({
438 queryKey: ['dependant2'],
439 queryFn: dependentQueryFn,
440 enabled: !!this.query1.data(),
441 })),
442 )
443 }
444
445 const fixture = TestBed.createComponent(TestComponent)
446 fixture.detectChanges()
447 const { query1, query2 } = fixture.componentInstance
448
449 expect(query1.data()).toStrictEqual(undefined)
450 expect(query2.fetchStatus()).toStrictEqual('idle')
451 expect(dependentQueryFn).not.toHaveBeenCalled()
452
453 await vi.advanceTimersByTimeAsync(11)
454
455 expect(query1.data()).toStrictEqual('Some data')
456 expect(query2.fetchStatus()).toStrictEqual('fetching')
457
458 await vi.advanceTimersByTimeAsync(1002)
459
460 expect(query2.fetchStatus()).toStrictEqual('idle')
461 expect(query2.status()).toStrictEqual('success')
462 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
463 expect(dependentQueryFn).toHaveBeenCalledWith(
464 expect.objectContaining({ queryKey: ['dependant2'] }),
465 )
466 })
467
468 test('should use the current value for the queryKey when refetch is called', async () => {
469 const fetchFn = vi.fn(() => sleep(10).then(() => 'Some data'))
470 const keySignal = signal('key11')
471
472 @Component({
473 selector: 'app-test',
474 template: '',
475 changeDetection: ChangeDetectionStrategy.OnPush,
476 })
477 class TestComponent {
478 keySignal = keySignal
479 fetchFn = fetchFn
480 query = injectQuery(() => ({
481 queryKey: ['key10', this.keySignal()],
482 queryFn: this.fetchFn,
483 enabled: false,
484 }))
485 }
486
487 const fixture = TestBed.createComponent(TestComponent)
488 fixture.detectChanges()
489 const query = fixture.componentInstance.query
490
491 expect(fetchFn).not.toHaveBeenCalled()
492
493 void query.refetch().then(() => {
494 expect(fetchFn).toHaveBeenCalledTimes(1)
495 expect(fetchFn).toHaveBeenCalledWith(
496 expect.objectContaining({
497 queryKey: ['key10', 'key11'],
498 }),
499 )
500 })
501
502 await vi.advanceTimersByTimeAsync(11)
503
504 keySignal.set('key12')
505 fixture.detectChanges()
506
507 void query.refetch().then(() => {
508 expect(fetchFn).toHaveBeenCalledTimes(2)
509 expect(fetchFn).toHaveBeenCalledWith(
510 expect.objectContaining({
511 queryKey: ['key10', 'key12'],
512 }),
513 )
514 })
515
516 await vi.advanceTimersByTimeAsync(11)
517 })
518
519 test('should support selection function with select', async () => {
520 const app = TestBed.inject(ApplicationRef)
521
522 @Component({
523 selector: 'app-test',
524 template: '',
525 changeDetection: ChangeDetectionStrategy.OnPush,
526 })
527 class TestComponent {
528 query = injectQuery(() => ({
529 queryKey: ['key13'],
530 queryFn: () => [{ id: 1 }, { id: 2 }],
531 select: (data) => data.map((item) => item.id),
532 }))
533 }
534
535 const fixture = TestBed.createComponent(TestComponent)
536 fixture.detectChanges()
537 const query = fixture.componentInstance.query
538
539 // Wait for query to complete (even synchronous queryFn needs time to process)
540 const stablePromise = app.whenStable()
541 await Promise.resolve()
542 await vi.advanceTimersByTimeAsync(10)
543 await stablePromise
544
545 expect(query.status()).toBe('success')
546 expect(query.data()).toEqual([1, 2])
547 })
548
549 describe('throwOnError', () => {
550 test('should evaluate throwOnError when query is expected to throw', async () => {
551 const boundaryFn = vi.fn()
552
553 @Component({
554 selector: 'app-test',
555 template: '',
556 changeDetection: ChangeDetectionStrategy.OnPush,
557 })
558 class TestComponent {
559 boundaryFn = boundaryFn
560 query = injectQuery(() => ({
561 queryKey: ['key12'],
562 queryFn: () =>
563 sleep(10).then(() => Promise.reject(new Error('Some error'))),
564 retry: false,
565 throwOnError: this.boundaryFn,
566 }))
567 }
568
569 const fixture = TestBed.createComponent(TestComponent)
570 fixture.detectChanges()
571
572 await vi.advanceTimersByTimeAsync(11)
573 expect(boundaryFn).toHaveBeenCalledTimes(1)
574 expect(boundaryFn).toHaveBeenCalledWith(
575 Error('Some error'),
576 expect.objectContaining({
577 state: expect.objectContaining({ status: 'error' }),
578 }),
579 )
580 })
581
582 test('should throw when throwOnError is true', async () => {
583 const zone = TestBed.inject(NgZone)
584 const zoneErrorPromise = new Promise<Error>((resolve) => {
585 const sub = zone.onError.subscribe((error) => {
586 sub.unsubscribe()
587 resolve(error as Error)
588 })
589 })
590 let handler: ((error: Error) => void) | null = null
591 const processErrorPromise = new Promise<Error>((resolve) => {
592 handler = (error: Error) => {
593 process.off('uncaughtException', handler!)
594 resolve(error)
595 }
596 process.on('uncaughtException', handler)
597 })
598
599 @Component({
600 selector: 'app-test',
601 template: '',
602 changeDetection: ChangeDetectionStrategy.OnPush,
603 })
604 class TestComponent {
605 query = injectQuery(() => ({
606 queryKey: ['key13'],
607 queryFn: () =>
608 sleep(0).then(() => Promise.reject(new Error('Some error'))),
609 throwOnError: true,
610 }))
611 }
612
613 TestBed.createComponent(TestComponent).detectChanges()
614
615 try {
616 await vi.runAllTimersAsync()
617 await expect(zoneErrorPromise).resolves.toEqual(Error('Some error'))
618 await expect(processErrorPromise).resolves.toEqual(Error('Some error'))
619 } finally {
620 if (handler) {
621 process.off('uncaughtException', handler)
622 }
623 }
624 })
625
626 test('should throw when throwOnError function returns true', async () => {
627 const zone = TestBed.inject(NgZone)
628 const zoneErrorPromise = new Promise<Error>((resolve) => {
629 const sub = zone.onError.subscribe((error) => {
630 sub.unsubscribe()
631 resolve(error as Error)
632 })
633 })
634 let handler: ((error: Error) => void) | null = null
635 const processErrorPromise = new Promise<Error>((resolve) => {
636 handler = (error: Error) => {
637 process.off('uncaughtException', handler!)
638 resolve(error)
639 }
640 process.on('uncaughtException', handler)
641 })
642
643 @Component({
644 selector: 'app-test',
645 template: '',
646 changeDetection: ChangeDetectionStrategy.OnPush,
647 })
648 class TestComponent {
649 query = injectQuery(() => ({
650 queryKey: ['key14'],
651 queryFn: () =>
652 sleep(0).then(() => Promise.reject(new Error('Some error'))),
653 throwOnError: () => true,
654 }))
655 }
656
657 TestBed.createComponent(TestComponent).detectChanges()
658
659 try {
660 await vi.runAllTimersAsync()
661 await expect(zoneErrorPromise).resolves.toEqual(Error('Some error'))
662 await expect(processErrorPromise).resolves.toEqual(Error('Some error'))
663 } finally {
664 if (handler) {
665 process.off('uncaughtException', handler)
666 }
667 }
668 })
669 })
670
671 test('should set state to error when queryFn returns reject promise', async () => {
672 @Component({
673 selector: 'app-test',
674 template: '',
675 changeDetection: ChangeDetectionStrategy.OnPush,
676 })
677 class TestComponent {
678 query = injectQuery(() => ({
679 retry: false,
680 queryKey: ['key15'],
681 queryFn: () =>
682 sleep(10).then(() => Promise.reject(new Error('Some error'))),
683 }))
684 }
685
686 const fixture = TestBed.createComponent(TestComponent)
687 fixture.detectChanges()
688 const query = fixture.componentInstance.query
689
690 expect(query.status()).toBe('pending')
691
692 await vi.advanceTimersByTimeAsync(11)
693
694 expect(query.status()).toBe('error')
695 })
696
697 test('should render with required signal inputs', async () => {
698 @Component({
699 selector: 'app-fake',
700 template: `{{ query.data() }}`,
701 changeDetection: ChangeDetectionStrategy.OnPush,
702 })
703 class FakeComponent {
704 name = input.required<string>()
705
706 query = injectQuery(() => ({
707 queryKey: ['fake', this.name()],
708 queryFn: () => this.name(),
709 }))
710 }
711
712 registerSignalInput(FakeComponent, 'name')
713
714 @Component({
715 template: `<app-fake [name]="name()" />`,
716 imports: [FakeComponent],
717 })
718 class HostComponent {
719 protected readonly name = signal('signal-input-required-test')
720 }
721
722 const fixture = TestBed.createComponent(HostComponent)
723 fixture.detectChanges()
724 await vi.advanceTimersByTimeAsync(0)
725
726 const result = fixture.nativeElement.querySelector('app-fake').textContent
727 expect(result).toEqual('signal-input-required-test')
728 })
729
730 test('should support aliasing query.data on required signal inputs', async () => {
731 @Component({
732 selector: 'app-fake',
733 template: `{{ data() }}`,
734 changeDetection: ChangeDetectionStrategy.OnPush,
735 })
736 class FakeComponent {
737 name = input.required<string>()
738
739 query = injectQuery(() => ({
740 queryKey: ['fake-alias', this.name()],
741 queryFn: () => this.name(),
742 }))
743
744 data = this.query.data
745 }
746
747 registerSignalInput(FakeComponent, 'name')
748
749 @Component({
750 template: `<app-fake [name]="name()" />`,
751 imports: [FakeComponent],
752 })
753 class HostComponent {
754 protected readonly name = signal('signal-input-alias-test')
755 }
756
757 const fixture = TestBed.createComponent(HostComponent)
758 fixture.detectChanges()
759 await vi.advanceTimersByTimeAsync(0)
760
761 const result = fixture.nativeElement.querySelector('app-fake').textContent
762 expect(result).toEqual('signal-input-alias-test')
763 })
764
765 test('should allow reading the query data on effect registered before injection', () => {
766 const spy = vi.fn()
767 @Component({
768 selector: 'app-test',
769 template: '',
770 changeDetection: ChangeDetectionStrategy.OnPush,
771 })
772 class TestComponent {
773 readEffect = effect(() => {
774 spy(this.query.data())
775 })
776
777 query = injectQuery(() => ({
778 queryKey: ['effect-before-injection'],
779 queryFn: () => sleep(0).then(() => 'Some data'),
780 }))
781 }
782
783 const fixture = TestBed.createComponent(TestComponent)
784 fixture.detectChanges()
785 expect(spy).toHaveBeenCalledWith(undefined)
786 })
787
788 test('should render with an initial value for input signal if available before change detection', () => {
789 const key1 = queryKey()
790 const key2 = queryKey()
791
792 queryClient.setQueryData(key1, 'value 1')
793 queryClient.setQueryData(key2, 'value 2')
794
795 @Component({
796 selector: 'app-test',
797 template: '{{ query.data() }}',
798 changeDetection: ChangeDetectionStrategy.OnPush,
799 })
800 class TestComponent {
801 inputKey = input.required<[string]>()
802 query = injectQuery(() => ({
803 queryKey: this.inputKey(),
804 queryFn: () => sleep(0).then(() => 'Some data'),
805 }))
806 }
807 registerSignalInput(TestComponent, 'inputKey')
808
809 const fixture = TestBed.createComponent(TestComponent)
810 fixture.componentRef.setInput('inputKey', key1)
811
812 const instance = fixture.componentInstance
813 const query = instance.query
814
815 expect(() => instance.inputKey()).not.toThrow()
816
817 expect(instance.inputKey()).toEqual(key1)
818 expect(query.data()).toEqual('value 1')
819
820 fixture.componentRef.setInput('inputKey', key2)
821
822 expect(instance.inputKey()).toEqual(key2)
823 expect(query.data()).toEqual('value 2')
824 })
825
826 test('should allow reading the query data on component ngOnInit with required signal input', async () => {
827 const spy = vi.fn()
828 @Component({
829 selector: 'app-test',
830 template: '',
831 changeDetection: ChangeDetectionStrategy.OnPush,
832 })
833 class TestComponent {
834 key = input.required<[string]>()
835 query = injectQuery(() => ({
836 queryKey: this.key(),
837 queryFn: () => Promise.resolve(() => 'Some data'),
838 }))
839
840 initialStatus!: string
841
842 ngOnInit() {
843 this.initialStatus = this.query.status()
844
845 // effect should not have been called yet
846 expect(spy).not.toHaveBeenCalled()
847 }
848
849 _spyEffect = effect(() => {
850 spy()
851 })
852 }
853
854 registerSignalInput(TestComponent, 'key')
855
856 const fixture = TestBed.createComponent(TestComponent)
857 fixture.componentRef.setInput('key', ['ngOnInitTest'])
858
859 fixture.detectChanges()
860 expect(spy).toHaveBeenCalled()
861
862 const instance = fixture.componentInstance
863 expect(instance.initialStatus).toEqual('pending')
864 })
865
866 test('should update query data on the same macro task when query data changes', async () => {
867 const query = TestBed.runInInjectionContext(() =>
868 injectQuery(() => ({
869 queryKey: ['test'],
870 initialData: 'initial data',
871 })),
872 )
873
874 // Run effects
875 TestBed.tick()
876
877 expect(query.data()).toBe('initial data')
878 queryClient.setQueryData(['test'], 'new data')
879
880 // Flush microtasks
881 await Promise.resolve()
882
883 expect(query.data()).toBe('new data')
884 })
885
886 test('should pause fetching while restoring and fetch once restoring is disabled', async () => {
887 const isRestoring = signal(true)
888 const fetchSpy = vi.fn(() => sleep(10).then(() => 'restored-data'))
889
890 TestBed.resetTestingModule()
891 TestBed.configureTestingModule({
892 providers: [
893 provideZonelessChangeDetection(),
894 provideTanStackQuery(queryClient),
895 provideIsRestoring(isRestoring.asReadonly()),
896 ],
897 })
898
899 @Component({
900 selector: 'app-test',
901 template: '',
902 changeDetection: ChangeDetectionStrategy.OnPush,
903 })
904 class TestComponent {
905 query = injectQuery(() => ({
906 queryKey: ['restoring'],
907 queryFn: fetchSpy,
908 }))
909 }
910
911 const fixture = TestBed.createComponent(TestComponent)
912 fixture.detectChanges()
913
914 const query = fixture.componentInstance.query
915 expect(fetchSpy).not.toHaveBeenCalled()
916 expect(query.status()).toBe('pending')
917
918 const stablePromise = fixture.whenStable()
919 await Promise.resolve()
920 await stablePromise
921
922 isRestoring.set(false)
923 fixture.detectChanges()
924
925 await vi.advanceTimersByTimeAsync(11)
926 await fixture.whenStable()
927
928 expect(fetchSpy).toHaveBeenCalledTimes(1)
929 expect(query.status()).toBe('success')
930 expect(query.data()).toBe('restored-data')
931 })
932
933 describe('injection context', () => {
934 test('throws NG0203 with descriptive error outside injection context', () => {
935 expect(() => {
936 injectQuery(() => ({
937 queryKey: ['injectionContextError'],
938 queryFn: () => sleep(0).then(() => 'Some data'),
939 }))
940 }).toThrowError(/NG0203(.*?)injectQuery/)
941 })
942
943 test('can be used outside injection context when passing an injector', () => {
944 const injector = TestBed.inject(Injector)
945
946 @Component({
947 selector: 'app-test',
948 template: '',
949 changeDetection: ChangeDetectionStrategy.OnPush,
950 })
951 class TestComponent {
952 query = injectQuery(
953 () => ({
954 queryKey: ['manualInjector'],
955 queryFn: () => sleep(0).then(() => 'Some data'),
956 }),
957 {
958 injector: injector,
959 },
960 )
961 }
962
963 const fixture = TestBed.createComponent(TestComponent)
964 fixture.detectChanges()
965 const query = fixture.componentInstance.query
966
967 expect(query.status()).toBe('pending')
968 })
969
970 test('should complete queries before whenStable() resolves', async () => {
971 const app = TestBed.inject(ApplicationRef)
972
973 @Component({
974 selector: 'app-test',
975 template: '',
976 changeDetection: ChangeDetectionStrategy.OnPush,
977 })
978 class TestComponent {
979 query = injectQuery(() => ({
980 queryKey: ['pendingTasksTest'],
981 queryFn: async () => {
982 await sleep(50)
983 return 'test data'
984 },
985 }))
986 }
987
988 const fixture = TestBed.createComponent(TestComponent)
989 fixture.detectChanges()
990 const query = fixture.componentInstance.query
991
992 expect(query.status()).toBe('pending')
993 expect(query.data()).toBeUndefined()
994
995 await vi.advanceTimersByTimeAsync(60)
996 await app.whenStable()
997
998 expect(query.status()).toBe('success')
999 expect(query.data()).toBe('test data')
1000 })
1001
1002 test('should complete HttpClient-based queries before whenStable() resolves', async () => {
1003 TestBed.resetTestingModule()
1004 TestBed.configureTestingModule({
1005 providers: [
1006 provideZonelessChangeDetection(),
1007 provideTanStackQuery(queryClient),
1008 provideHttpClient(),
1009 provideHttpClientTesting(),
1010 ],
1011 })
1012
1013 const app = TestBed.inject(ApplicationRef)
1014 const httpClient = TestBed.inject(HttpClient)
1015 const httpTestingController = TestBed.inject(HttpTestingController)
1016
1017 @Component({
1018 selector: 'app-test',
1019 template: '',
1020 changeDetection: ChangeDetectionStrategy.OnPush,
1021 })
1022 class TestComponent {
1023 httpClient = httpClient
1024 query = injectQuery(() => ({
1025 queryKey: ['httpClientTest'],
1026 queryFn: () =>
1027 lastValueFrom(
1028 this.httpClient.get<{ message: string }>('/api/test'),
1029 ),
1030 }))
1031 }
1032
1033 const fixture = TestBed.createComponent(TestComponent)
1034 fixture.detectChanges()
1035 const query = fixture.componentInstance.query
1036
1037 // Schedule the HTTP response
1038 setTimeout(() => {
1039 const req = httpTestingController.expectOne('/api/test')
1040 req.flush({ message: 'http test data' })
1041 }, 10)
1042
1043 // Initial state
1044 expect(query.status()).toBe('pending')
1045
1046 // Advance timers and wait for Angular to be "stable"
1047 await vi.advanceTimersByTimeAsync(20)
1048 await app.whenStable()
1049
1050 // Query should be complete after whenStable() thanks to PendingTasks integration
1051 expect(query.status()).toBe('success')
1052 expect(query.data()).toEqual({ message: 'http test data' })
1053
1054 httpTestingController.verify()
1055 })
1056
1057 test('should handle synchronous queryFn with staleTime', async () => {
1058 TestBed.resetTestingModule()
1059 TestBed.configureTestingModule({
1060 providers: [
1061 provideZonelessChangeDetection(),
1062 provideTanStackQuery(queryClient),
1063 ],
1064 })
1065
1066 const app = TestBed.inject(ApplicationRef)
1067
1068 @Component({
1069 selector: 'app-test',
1070 template: '',
1071 changeDetection: ChangeDetectionStrategy.OnPush,
1072 })
1073 class TestComponent {
1074 callCount = 0
1075 query = injectQuery(() => ({
1076 queryKey: ['sync-stale'],
1077 staleTime: 1000,
1078 queryFn: () => {
1079 this.callCount++
1080 return `sync-data-${this.callCount}`
1081 },
1082 }))
1083 }
1084
1085 const fixture = TestBed.createComponent(TestComponent)
1086 fixture.detectChanges()
1087 const component = fixture.componentInstance
1088 const query = component.query
1089
1090 const stablePromise = app.whenStable()
1091 await vi.advanceTimersToNextTimerAsync()
1092 await stablePromise
1093
1094 expect(query.status()).toBe('success')
1095 expect(query.data()).toBe('sync-data-1')
1096 expect(component.callCount).toBe(1)
1097
1098 await query.refetch()
1099 await Promise.resolve()
1100 await vi.runAllTimersAsync()
1101 await app.whenStable()
1102
1103 expect(query.status()).toBe('success')
1104 expect(query.data()).toBe('sync-data-2')
1105 expect(component.callCount).toBe(2)
1106 })
1107
1108 test('should handle enabled/disabled transitions with synchronous queryFn', async () => {
1109 TestBed.resetTestingModule()
1110 TestBed.configureTestingModule({
1111 providers: [
1112 provideZonelessChangeDetection(),
1113 provideTanStackQuery(queryClient),
1114 ],
1115 })
1116
1117 const app = TestBed.inject(ApplicationRef)
1118 const enabledSignal = signal(false)
1119
1120 @Component({
1121 selector: 'app-test',
1122 template: '',
1123 changeDetection: ChangeDetectionStrategy.OnPush,
1124 })
1125 class TestComponent {
1126 enabledSignal = enabledSignal
1127 callCount = 0
1128 query = injectQuery(() => ({
1129 queryKey: ['sync-enabled'],
1130 enabled: this.enabledSignal(),
1131 queryFn: () => {
1132 this.callCount++
1133 return `sync-data-${this.callCount}`
1134 },
1135 }))
1136 }
1137
1138 const fixture = TestBed.createComponent(TestComponent)
1139 fixture.detectChanges()
1140 const component = fixture.componentInstance
1141 const query = component.query
1142
1143 // Initially disabled
1144 await vi.advanceTimersByTimeAsync(0)
1145 await app.whenStable()
1146 expect(query.status()).toBe('pending')
1147 expect(query.data()).toBeUndefined()
1148 expect(component.callCount).toBe(0)
1149
1150 // Enable the query
1151 enabledSignal.set(true)
1152 fixture.detectChanges()
1153
1154 const stablePromise = app.whenStable()
1155 await vi.advanceTimersToNextTimerAsync()
1156 await stablePromise
1157
1158 expect(query.status()).toBe('success')
1159 expect(query.data()).toBe('sync-data-1')
1160 expect(component.callCount).toBe(1)
1161 })
1162
1163 test('should handle query invalidation with synchronous data', async () => {
1164 TestBed.resetTestingModule()
1165 TestBed.configureTestingModule({
1166 providers: [
1167 provideZonelessChangeDetection(),
1168 provideTanStackQuery(queryClient),
1169 ],
1170 })
1171
1172 const app = TestBed.inject(ApplicationRef)
1173 const testKey = ['sync-invalidate']
1174
1175 @Component({
1176 selector: 'app-test',
1177 template: '',
1178 changeDetection: ChangeDetectionStrategy.OnPush,
1179 })
1180 class TestComponent {
1181 callCount = 0
1182 query = injectQuery(() => ({
1183 queryKey: testKey,
1184 queryFn: () => {
1185 this.callCount++
1186 return `sync-data-${this.callCount}`
1187 },
1188 }))
1189 }
1190
1191 const fixture = TestBed.createComponent(TestComponent)
1192 fixture.detectChanges()
1193 const component = fixture.componentInstance
1194 const query = component.query
1195
1196 const stablePromise = app.whenStable()
1197 await vi.advanceTimersToNextTimerAsync()
1198 await stablePromise
1199
1200 expect(query.status()).toBe('success')
1201 expect(query.data()).toBe('sync-data-1')
1202 expect(component.callCount).toBe(1)
1203
1204 // Invalidate the query
1205 queryClient.invalidateQueries({ queryKey: testKey })
1206
1207 // Wait for the invalidation to trigger a refetch
1208 await Promise.resolve()
1209 await vi.advanceTimersByTimeAsync(10)
1210
1211 await app.whenStable()
1212 expect(query.status()).toBe('success')
1213 expect(query.data()).toBe('sync-data-2')
1214 expect(component.callCount).toBe(2)
1215 })
1216 })
1217})