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

inject-query.test.ts

1,204 lines34.6 KB

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