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

inject-query.test.ts

972 lines28.3 KB

1import {
2 ApplicationRef,
3 ChangeDetectionStrategy,
4 Component,
5 Injector,
6 NgZone,
7 computed,
8 input,
9 provideZonelessChangeDetection,
10 signal,
11} from '@angular/core'
12import { TestBed } from '@angular/core/testing'
13import { HttpClient, provideHttpClient } from '@angular/common/http'
14import {
15 HttpTestingController,
16 provideHttpClientTesting,
17} from '@angular/common/http/testing'
18import {
19 afterEach,
20 beforeEach,
21 describe,
22 expect,
23 expectTypeOf,
24 test,
25 vi,
26} from 'vitest'
27import { queryKey, sleep } from '@tanstack/query-test-utils'
28import { lastValueFrom } from 'rxjs'
29import { QueryCache, QueryClient, injectQuery, provideTanStackQuery } from '..'
30import { registerSignalInput } from './test-utils'
31import type { CreateQueryOptions, OmitKeyof, QueryFunction } from '..'
32​
33describe('injectQuery', () => {
34 let queryCache: QueryCache
35 let queryClient: QueryClient
36 beforeEach(() => {
37 vi.useFakeTimers()
38 queryCache = new QueryCache()
39 queryClient = new QueryClient({ queryCache })
40 TestBed.configureTestingModule({
41 providers: [
42 provideZonelessChangeDetection(),
43 provideTanStackQuery(queryClient),
44 ],
45 })
46 })
47​
48 afterEach(() => {
49 vi.useRealTimers()
50 })
51​
52 test('should return the correct types', () => {
53 const key = queryKey()
54​
55 @Component({
56 selector: 'app-test',
57 template: '',
58 changeDetection: ChangeDetectionStrategy.OnPush,
59 })
60 class TestComponent {
61 // unspecified query function should default to unknown
62 noQueryFn = injectQuery(() => ({
63 queryKey: key,
64 }))
65​
66 // it should infer the result type from the query function
67 fromQueryFn = injectQuery(() => ({
68 queryKey: key,
69 queryFn: () => 'test',
70 }))
71​
72 // it should be possible to specify the result type
73 withResult = injectQuery<string>(() => ({
74 queryKey: key,
75 queryFn: () => 'test',
76 }))
77​
78 // it should be possible to specify the error type
79 withError = injectQuery<string, { message: string }>(() => ({
80 queryKey: key,
81 queryFn: () => 'test',
82 }))
83​
84 // it should infer the result type from the configuration
85 withResultInfer = injectQuery(() => ({
86 queryKey: key,
87 queryFn: () => true,
88 }))
89​
90 // it should be possible to specify a union type as result type
91 unionTypeSync = injectQuery(() => ({
92 queryKey: key,
93 queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
94 }))
95​
96 unionTypeAsync = injectQuery<'a' | 'b'>(() => ({
97 queryKey: key,
98 queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
99 }))
100​
101 // it should infer the result type from a generic query function
102 fromGenericQueryFn = (() => {
103 function queryFn<T = string>(): Promise<T> {
104 return Promise.resolve({} as T)
105 }
106 return injectQuery(() => ({
107 queryKey: key,
108 queryFn: () => queryFn(),
109 }))
110 })()
111​
112 // todo use query options?
113 fromGenericOptionsQueryFn = (() => {
114 function queryFn<T = string>(): Promise<T> {
115 return Promise.resolve({} as T)
116 }
117 return injectQuery(() => ({
118 queryKey: key,
119 queryFn: () => queryFn(),
120 }))
121 })()
122​
123 fromMyDataArrayKeyQueryFn = (() => {
124 type MyData = number
125 type MyQueryKey = readonly ['my-data', number]
126 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
127 queryKey: [, n],
128 }) => {
129 return n + 42
130 }
131 return injectQuery(() => ({
132 queryKey: ['my-data', 100] as const,
133 queryFn: getMyDataArrayKey,
134 }))
135 })()
136​
137 // it should handle query-functions that return Promise<any>
138 fromPromiseAnyQueryFn = injectQuery(() => ({
139 queryKey: key,
140 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
141 }))
142​
143 fromGetMyDataStringKeyQueryFn = (() => {
144 type MyData = number
145 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
146 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
147 return Number(context.queryKey[0]) + 42
148 }
149 return injectQuery(() => ({
150 queryKey: ['1'] as ['1'],
151 queryFn: getMyDataStringKey,
152 }))
153 })()
154​
155 // Wrapped queries
156 fromWrappedQuery = (() => {
157 const createWrappedQuery = <
158 TQueryKey extends [string, Record<string, unknown>?],
159 TQueryFnData,
160 TError,
161 TData = TQueryFnData,
162 >(
163 qk: TQueryKey,
164 fetcher: (obj: TQueryKey[1], token: string) => Promise<TQueryFnData>,
165 options?: OmitKeyof<
166 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
167 'queryKey' | 'queryFn' | 'initialData',
168 'safely'
169 >,
170 ) =>
171 injectQuery(() => ({
172 queryKey: qk,
173 queryFn: () => fetcher(qk[1], 'token'),
174 ...options,
175 }))
176 return createWrappedQuery([''], () => Promise.resolve('1'))
177 })()
178​
179 fromWrappedFuncStyleQuery = (() => {
180 const createWrappedFuncStyleQuery = <
181 TQueryKey extends [string, Record<string, unknown>?],
182 TQueryFnData,
183 TError,
184 TData = TQueryFnData,
185 >(
186 qk: TQueryKey,
187 fetcher: () => Promise<TQueryFnData>,
188 options?: OmitKeyof<
189 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
190 'queryKey' | 'queryFn' | 'initialData',
191 'safely'
192 >,
193 ) => injectQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
194 return createWrappedFuncStyleQuery([''], () => Promise.resolve(true))
195 })()
196 }
197​
198 const fixture = TestBed.createComponent(TestComponent)
199 fixture.detectChanges()
200 const {
201 noQueryFn,
202 fromQueryFn,
203 withResult,
204 withError,
205 withResultInfer,
206 unionTypeSync,
207 unionTypeAsync,
208 fromGenericQueryFn,
209 fromGenericOptionsQueryFn,
210 fromMyDataArrayKeyQueryFn,
211 fromPromiseAnyQueryFn,
212 fromGetMyDataStringKeyQueryFn,
213 fromWrappedQuery,
214 fromWrappedFuncStyleQuery,
215 } = fixture.componentInstance
216​
217 expectTypeOf(noQueryFn.data()).toEqualTypeOf<unknown>()
218 expectTypeOf(noQueryFn.error()).toEqualTypeOf<Error | null>()
219​
220 expectTypeOf(fromQueryFn.data()).toEqualTypeOf<string | undefined>()
221 expectTypeOf(fromQueryFn.error()).toEqualTypeOf<Error | null>()
222​
223 expectTypeOf(withResult.data()).toEqualTypeOf<string | undefined>()
224 expectTypeOf(withResult.error()).toEqualTypeOf<Error | null>()
225​
226 expectTypeOf(withError.data()).toEqualTypeOf<string | undefined>()
227 expectTypeOf(withError.error()).toEqualTypeOf<{ message: string } | null>()
228​
229 expectTypeOf(withResultInfer.data()).toEqualTypeOf<boolean | undefined>()
230 expectTypeOf(withResultInfer.error()).toEqualTypeOf<Error | null>()
231​
232 expectTypeOf(unionTypeSync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
233 expectTypeOf(unionTypeAsync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
234​
235 expectTypeOf(fromGenericQueryFn.data()).toEqualTypeOf<string | undefined>()
236 expectTypeOf(fromGenericQueryFn.error()).toEqualTypeOf<Error | null>()
237​
238 expectTypeOf(fromGenericOptionsQueryFn.data()).toEqualTypeOf<
239 string | undefined
240 >()
241 expectTypeOf(
242 fromGenericOptionsQueryFn.error(),
243 ).toEqualTypeOf<Error | null>()
244​
245 expectTypeOf(fromMyDataArrayKeyQueryFn.data()).toEqualTypeOf<
246 number | undefined
247 >()
248​
249 expectTypeOf(fromPromiseAnyQueryFn.data()).toEqualTypeOf<any | undefined>()
250​
251 expectTypeOf(fromGetMyDataStringKeyQueryFn.data()).toEqualTypeOf<
252 number | undefined
253 >()
254​
255 expectTypeOf(fromWrappedQuery.data()).toEqualTypeOf<string | undefined>()
256 expectTypeOf(fromWrappedFuncStyleQuery.data()).toEqualTypeOf<
257 boolean | undefined
258 >()
259 })
260​
261 test('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 test('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 test('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 test('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 test('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 test('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: ['dependant2'],
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: ['dependant2'] }),
460 )
461 })
462​
463 test('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 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 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 describe('throwOnError', () => {
515 test('should evaluate throwOnError when query is expected to throw', async () => {
516 const boundaryFn = vi.fn()
517​
518 @Component({
519 selector: 'app-test',
520 template: '',
521 changeDetection: ChangeDetectionStrategy.OnPush,
522 })
523 class TestComponent {
524 boundaryFn = boundaryFn
525 query = injectQuery(() => ({
526 queryKey: ['key12'],
527 queryFn: () =>
528 sleep(10).then(() => Promise.reject(new Error('Some error'))),
529 retry: false,
530 throwOnError: this.boundaryFn,
531 }))
532 }
533​
534 const fixture = TestBed.createComponent(TestComponent)
535 fixture.detectChanges()
536​
537 await vi.advanceTimersByTimeAsync(11)
538 expect(boundaryFn).toHaveBeenCalledTimes(1)
539 expect(boundaryFn).toHaveBeenCalledWith(
540 Error('Some error'),
541 expect.objectContaining({
542 state: expect.objectContaining({ status: 'error' }),
543 }),
544 )
545 })
546​
547 test('should throw when throwOnError is true', async () => {
548 const zone = TestBed.inject(NgZone)
549 const zoneErrorPromise = new Promise<Error>((resolve) => {
550 const sub = zone.onError.subscribe((error) => {
551 sub.unsubscribe()
552 resolve(error as Error)
553 })
554 })
555 let handler: ((error: Error) => void) | null = null
556 const processErrorPromise = new Promise<Error>((resolve) => {
557 handler = (error: Error) => {
558 process.off('uncaughtException', handler!)
559 resolve(error)
560 }
561 process.on('uncaughtException', handler)
562 })
563​
564 @Component({
565 selector: 'app-test',
566 template: '',
567 changeDetection: ChangeDetectionStrategy.OnPush,
568 })
569 class TestComponent {
570 query = injectQuery(() => ({
571 queryKey: ['key13'],
572 queryFn: () =>
573 sleep(0).then(() => Promise.reject(new Error('Some error'))),
574 throwOnError: true,
575 }))
576 }
577​
578 TestBed.createComponent(TestComponent).detectChanges()
579​
580 try {
581 await vi.runAllTimersAsync()
582 await expect(zoneErrorPromise).resolves.toEqual(Error('Some error'))
583 await expect(processErrorPromise).resolves.toEqual(Error('Some error'))
584 } finally {
585 if (handler) {
586 process.off('uncaughtException', handler)
587 }
588 }
589 })
590​
591 test('should throw when throwOnError function returns true', async () => {
592 const zone = TestBed.inject(NgZone)
593 const zoneErrorPromise = new Promise<Error>((resolve) => {
594 const sub = zone.onError.subscribe((error) => {
595 sub.unsubscribe()
596 resolve(error as Error)
597 })
598 })
599 let handler: ((error: Error) => void) | null = null
600 const processErrorPromise = new Promise<Error>((resolve) => {
601 handler = (error: Error) => {
602 process.off('uncaughtException', handler!)
603 resolve(error)
604 }
605 process.on('uncaughtException', handler)
606 })
607​
608 @Component({
609 selector: 'app-test',
610 template: '',
611 changeDetection: ChangeDetectionStrategy.OnPush,
612 })
613 class TestComponent {
614 query = injectQuery(() => ({
615 queryKey: ['key14'],
616 queryFn: () =>
617 sleep(0).then(() => Promise.reject(new Error('Some error'))),
618 throwOnError: () => true,
619 }))
620 }
621​
622 TestBed.createComponent(TestComponent).detectChanges()
623​
624 try {
625 await vi.runAllTimersAsync()
626 await expect(zoneErrorPromise).resolves.toEqual(Error('Some error'))
627 await expect(processErrorPromise).resolves.toEqual(Error('Some error'))
628 } finally {
629 if (handler) {
630 process.off('uncaughtException', handler)
631 }
632 }
633 })
634 })
635​
636 test('should set state to error when queryFn returns reject promise', async () => {
637 @Component({
638 selector: 'app-test',
639 template: '',
640 changeDetection: ChangeDetectionStrategy.OnPush,
641 })
642 class TestComponent {
643 query = injectQuery(() => ({
644 retry: false,
645 queryKey: ['key15'],
646 queryFn: () =>
647 sleep(10).then(() => Promise.reject(new Error('Some error'))),
648 }))
649 }
650​
651 const fixture = TestBed.createComponent(TestComponent)
652 fixture.detectChanges()
653 const query = fixture.componentInstance.query
654​
655 expect(query.status()).toBe('pending')
656​
657 await vi.advanceTimersByTimeAsync(11)
658​
659 expect(query.status()).toBe('error')
660 })
661​
662 test('should render with required signal inputs', async () => {
663 @Component({
664 selector: 'app-fake',
665 template: `{{ query.data() }}`,
666 changeDetection: ChangeDetectionStrategy.OnPush,
667 })
668 class FakeComponent {
669 name = input.required<string>()
670​
671 query = injectQuery(() => ({
672 queryKey: ['fake', this.name()],
673 queryFn: () => this.name(),
674 }))
675 }
676​
677 registerSignalInput(FakeComponent, 'name')
678​
679 @Component({
680 template: `<app-fake [name]="name()" />`,
681 imports: [FakeComponent],
682 })
683 class HostComponent {
684 protected readonly name = signal('signal-input-required-test')
685 }
686​
687 const fixture = TestBed.createComponent(HostComponent)
688 fixture.detectChanges()
689 await vi.advanceTimersByTimeAsync(0)
690​
691 const result = fixture.nativeElement.querySelector('app-fake').textContent
692 expect(result).toEqual('signal-input-required-test')
693 })
694​
695 describe('injection context', () => {
696 test('throws NG0203 with descriptive error outside injection context', () => {
697 expect(() => {
698 injectQuery(() => ({
699 queryKey: ['injectionContextError'],
700 queryFn: () => sleep(0).then(() => 'Some data'),
701 }))
702 }).toThrowError(/NG0203(.*?)injectQuery/)
703 })
704​
705 test('can be used outside injection context when passing an injector', () => {
706 const injector = TestBed.inject(Injector)
707​
708 @Component({
709 selector: 'app-test',
710 template: '',
711 changeDetection: ChangeDetectionStrategy.OnPush,
712 })
713 class TestComponent {
714 query = injectQuery(
715 () => ({
716 queryKey: ['manualInjector'],
717 queryFn: () => sleep(0).then(() => 'Some data'),
718 }),
719 {
720 injector: injector,
721 },
722 )
723 }
724​
725 const fixture = TestBed.createComponent(TestComponent)
726 fixture.detectChanges()
727 const query = fixture.componentInstance.query
728​
729 expect(query.status()).toBe('pending')
730 })
731​
732 test('should complete queries before whenStable() resolves', async () => {
733 const app = TestBed.inject(ApplicationRef)
734​
735 @Component({
736 selector: 'app-test',
737 template: '',
738 changeDetection: ChangeDetectionStrategy.OnPush,
739 })
740 class TestComponent {
741 query = injectQuery(() => ({
742 queryKey: ['pendingTasksTest'],
743 queryFn: async () => {
744 await sleep(50)
745 return 'test data'
746 },
747 }))
748 }
749​
750 const fixture = TestBed.createComponent(TestComponent)
751 fixture.detectChanges()
752 const query = fixture.componentInstance.query
753​
754 expect(query.status()).toBe('pending')
755 expect(query.data()).toBeUndefined()
756​
757 await vi.advanceTimersByTimeAsync(60)
758 await app.whenStable()
759​
760 expect(query.status()).toBe('success')
761 expect(query.data()).toBe('test data')
762 })
763​
764 test('should complete HttpClient-based queries before whenStable() resolves', async () => {
765 TestBed.resetTestingModule()
766 TestBed.configureTestingModule({
767 providers: [
768 provideZonelessChangeDetection(),
769 provideTanStackQuery(queryClient),
770 provideHttpClient(),
771 provideHttpClientTesting(),
772 ],
773 })
774​
775 const app = TestBed.inject(ApplicationRef)
776 const httpClient = TestBed.inject(HttpClient)
777 const httpTestingController = TestBed.inject(HttpTestingController)
778​
779 @Component({
780 selector: 'app-test',
781 template: '',
782 changeDetection: ChangeDetectionStrategy.OnPush,
783 })
784 class TestComponent {
785 httpClient = httpClient
786 query = injectQuery(() => ({
787 queryKey: ['httpClientTest'],
788 queryFn: () =>
789 lastValueFrom(
790 this.httpClient.get<{ message: string }>('/api/test'),
791 ),
792 }))
793 }
794​
795 const fixture = TestBed.createComponent(TestComponent)
796 fixture.detectChanges()
797 const query = fixture.componentInstance.query
798​
799 // Schedule the HTTP response
800 setTimeout(() => {
801 const req = httpTestingController.expectOne('/api/test')
802 req.flush({ message: 'http test data' })
803 }, 10)
804​
805 // Initial state
806 expect(query.status()).toBe('pending')
807​
808 // Advance timers and wait for Angular to be "stable"
809 await vi.advanceTimersByTimeAsync(20)
810 await app.whenStable()
811​
812 // Query should be complete after whenStable() thanks to PendingTasks integration
813 expect(query.status()).toBe('success')
814 expect(query.data()).toEqual({ message: 'http test data' })
815​
816 httpTestingController.verify()
817 })
818​
819 test('should handle synchronous queryFn with staleTime', async () => {
820 TestBed.resetTestingModule()
821 TestBed.configureTestingModule({
822 providers: [
823 provideZonelessChangeDetection(),
824 provideTanStackQuery(queryClient),
825 ],
826 })
827​
828 const app = TestBed.inject(ApplicationRef)
829​
830 @Component({
831 selector: 'app-test',
832 template: '',
833 changeDetection: ChangeDetectionStrategy.OnPush,
834 })
835 class TestComponent {
836 callCount = 0
837 query = injectQuery(() => ({
838 queryKey: ['sync-stale'],
839 staleTime: 1000,
840 queryFn: () => {
841 this.callCount++
842 return `sync-data-${this.callCount}`
843 },
844 }))
845 }
846​
847 const fixture = TestBed.createComponent(TestComponent)
848 fixture.detectChanges()
849 const component = fixture.componentInstance
850 const query = component.query
851​
852 await app.whenStable()
853​
854 expect(query.status()).toBe('success')
855 expect(query.data()).toBe('sync-data-1')
856 expect(component.callCount).toBe(1)
857​
858 await query.refetch()
859 await Promise.resolve()
860 await vi.runAllTimersAsync()
861 await app.whenStable()
862​
863 expect(query.status()).toBe('success')
864 expect(query.data()).toBe('sync-data-2')
865 expect(component.callCount).toBe(2)
866 })
867​
868 test('should handle enabled/disabled transitions with synchronous queryFn', async () => {
869 TestBed.resetTestingModule()
870 TestBed.configureTestingModule({
871 providers: [
872 provideZonelessChangeDetection(),
873 provideTanStackQuery(queryClient),
874 ],
875 })
876​
877 const app = TestBed.inject(ApplicationRef)
878 const enabledSignal = signal(false)
879​
880 @Component({
881 selector: 'app-test',
882 template: '',
883 changeDetection: ChangeDetectionStrategy.OnPush,
884 })
885 class TestComponent {
886 enabledSignal = enabledSignal
887 callCount = 0
888 query = injectQuery(() => ({
889 queryKey: ['sync-enabled'],
890 enabled: this.enabledSignal(),
891 queryFn: () => {
892 this.callCount++
893 return `sync-data-${this.callCount}`
894 },
895 }))
896 }
897​
898 const fixture = TestBed.createComponent(TestComponent)
899 fixture.detectChanges()
900 const component = fixture.componentInstance
901 const query = component.query
902​
903 // Initially disabled
904 await vi.advanceTimersByTimeAsync(0)
905 await app.whenStable()
906 expect(query.status()).toBe('pending')
907 expect(query.data()).toBeUndefined()
908 expect(component.callCount).toBe(0)
909​
910 // Enable the query
911 enabledSignal.set(true)
912 fixture.detectChanges()
913​
914 await vi.advanceTimersByTimeAsync(0)
915 await app.whenStable()
916 expect(query.status()).toBe('success')
917 expect(query.data()).toBe('sync-data-1')
918 expect(component.callCount).toBe(1)
919 })
920​
921 test('should handle query invalidation with synchronous data', async () => {
922 TestBed.resetTestingModule()
923 TestBed.configureTestingModule({
924 providers: [
925 provideZonelessChangeDetection(),
926 provideTanStackQuery(queryClient),
927 ],
928 })
929​
930 const app = TestBed.inject(ApplicationRef)
931 const testKey = ['sync-invalidate']
932​
933 @Component({
934 selector: 'app-test',
935 template: '',
936 changeDetection: ChangeDetectionStrategy.OnPush,
937 })
938 class TestComponent {
939 callCount = 0
940 query = injectQuery(() => ({
941 queryKey: testKey,
942 queryFn: () => {
943 this.callCount++
944 return `sync-data-${this.callCount}`
945 },
946 }))
947 }
948​
949 const fixture = TestBed.createComponent(TestComponent)
950 fixture.detectChanges()
951 const component = fixture.componentInstance
952 const query = component.query
953​
954 await app.whenStable()
955 expect(query.status()).toBe('success')
956 expect(query.data()).toBe('sync-data-1')
957 expect(component.callCount).toBe(1)
958​
959 // Invalidate the query
960 queryClient.invalidateQueries({ queryKey: testKey })
961​
962 // Wait for the invalidation to trigger a refetch
963 await Promise.resolve()
964 await vi.advanceTimersByTimeAsync(10)
965​
966 await app.whenStable()
967 expect(query.status()).toBe('success')
968 expect(query.data()).toBe('sync-data-2')
969 expect(component.callCount).toBe(2)
970 })
971 })
972})