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

inject-query.test.ts

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