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

inject-query.test.ts

825 lines23.9 KB

1import {
2 ApplicationRef,
3 Component,
4 Injector,
5 computed,
6 effect,
7 input,
8 provideZonelessChangeDetection,
9 signal,
10} from '@angular/core'
11import { TestBed } from '@angular/core/testing'
12import { HttpClient, provideHttpClient } from '@angular/common/http'
13import {
14 HttpTestingController,
15 provideHttpClientTesting,
16} from '@angular/common/http/testing'
17import {
18 afterEach,
19 beforeEach,
20 describe,
21 expect,
22 expectTypeOf,
23 test,
24 vi,
25} from 'vitest'
26import { queryKey, sleep } from '@tanstack/query-test-utils'
27import { lastValueFrom } from 'rxjs'
28import {
29 QueryCache,
30 QueryClient,
31 injectQuery,
32 provideIsRestoring,
33 provideTanStackQuery,
34} from '..'
35import { setSignalInputs } from './test-utils'
36import type { CreateQueryOptions, OmitKeyof, QueryFunction } from '..'
37​
38describe('injectQuery', () => {
39 let queryCache: QueryCache
40 let queryClient: QueryClient
41 beforeEach(() => {
42 vi.useFakeTimers()
43 queryCache = new QueryCache()
44 queryClient = new QueryClient({ queryCache })
45 TestBed.configureTestingModule({
46 providers: [
47 provideZonelessChangeDetection(),
48 provideTanStackQuery(queryClient),
49 ],
50 })
51 })
52​
53 afterEach(() => {
54 vi.useRealTimers()
55 })
56​
57 test('should return the correct types', () => {
58 const key = queryKey()
59 // unspecified query function should default to unknown
60 const noQueryFn = TestBed.runInInjectionContext(() =>
61 injectQuery(() => ({
62 queryKey: key,
63 })),
64 )
65 expectTypeOf(noQueryFn.data()).toEqualTypeOf<unknown>()
66 expectTypeOf(noQueryFn.error()).toEqualTypeOf<Error | null>()
67​
68 // it should infer the result type from the query function
69 const fromQueryFn = TestBed.runInInjectionContext(() =>
70 injectQuery(() => ({
71 queryKey: key,
72 queryFn: () => 'test',
73 })),
74 )
75 expectTypeOf(fromQueryFn.data()).toEqualTypeOf<string | undefined>()
76 expectTypeOf(fromQueryFn.error()).toEqualTypeOf<Error | null>()
77​
78 // it should be possible to specify the result type
79 const withResult = TestBed.runInInjectionContext(() =>
80 injectQuery<string>(() => ({
81 queryKey: key,
82 queryFn: () => 'test',
83 })),
84 )
85 expectTypeOf(withResult.data()).toEqualTypeOf<string | undefined>()
86 expectTypeOf(withResult.error()).toEqualTypeOf<Error | null>()
87​
88 // it should be possible to specify the error type
89 type CustomErrorType = { message: string }
90 const withError = TestBed.runInInjectionContext(() =>
91 injectQuery<string, CustomErrorType>(() => ({
92 queryKey: key,
93 queryFn: () => 'test',
94 })),
95 )
96 expectTypeOf(withError.data()).toEqualTypeOf<string | undefined>()
97 expectTypeOf(withError.error()).toEqualTypeOf<CustomErrorType | null>()
98​
99 // it should infer the result type from the configuration
100 const withResultInfer = TestBed.runInInjectionContext(() =>
101 injectQuery(() => ({
102 queryKey: key,
103 queryFn: () => true,
104 })),
105 )
106 expectTypeOf(withResultInfer.data()).toEqualTypeOf<boolean | undefined>()
107 expectTypeOf(withResultInfer.error()).toEqualTypeOf<Error | null>()
108​
109 // it should be possible to specify a union type as result type
110 const unionTypeSync = TestBed.runInInjectionContext(() =>
111 injectQuery(() => ({
112 queryKey: key,
113 queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
114 })),
115 )
116 expectTypeOf(unionTypeSync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
117 const unionTypeAsync = TestBed.runInInjectionContext(() =>
118 injectQuery<'a' | 'b'>(() => ({
119 queryKey: key,
120 queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
121 })),
122 )
123 expectTypeOf(unionTypeAsync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
124​
125 // it should error when the query function result does not match with the specified type
126 TestBed.runInInjectionContext(() =>
127 // @ts-expect-error
128 injectQuery<number>(() => ({ queryKey: key, queryFn: () => 'test' })),
129 )
130​
131 // it should infer the result type from a generic query function
132 /**
133 *
134 */
135 function queryFn<T = string>(): Promise<T> {
136 return Promise.resolve({} as T)
137 }
138​
139 const fromGenericQueryFn = TestBed.runInInjectionContext(() =>
140 injectQuery(() => ({
141 queryKey: key,
142 queryFn: () => queryFn(),
143 })),
144 )
145 expectTypeOf(fromGenericQueryFn.data()).toEqualTypeOf<string | undefined>()
146 expectTypeOf(fromGenericQueryFn.error()).toEqualTypeOf<Error | null>()
147​
148 // todo use query options?
149 const fromGenericOptionsQueryFn = TestBed.runInInjectionContext(() =>
150 injectQuery(() => ({
151 queryKey: key,
152 queryFn: () => queryFn(),
153 })),
154 )
155 expectTypeOf(fromGenericOptionsQueryFn.data()).toEqualTypeOf<
156 string | undefined
157 >()
158 expectTypeOf(
159 fromGenericOptionsQueryFn.error(),
160 ).toEqualTypeOf<Error | null>()
161​
162 type MyData = number
163 type MyQueryKey = readonly ['my-data', number]
164​
165 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
166 queryKey: [, n],
167 }) => {
168 return n + 42
169 }
170​
171 const fromMyDataArrayKeyQueryFn = TestBed.runInInjectionContext(() =>
172 injectQuery(() => ({
173 queryKey: ['my-data', 100] as const,
174 queryFn: getMyDataArrayKey,
175 })),
176 )
177 expectTypeOf(fromMyDataArrayKeyQueryFn.data()).toEqualTypeOf<
178 number | undefined
179 >()
180​
181 // it should handle query-functions that return Promise<any>
182 const fromPromiseAnyQueryFn = TestBed.runInInjectionContext(() =>
183 injectQuery(() => ({
184 queryKey: key,
185 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
186 })),
187 )
188 expectTypeOf(fromPromiseAnyQueryFn.data()).toEqualTypeOf<any | undefined>()
189​
190 TestBed.runInInjectionContext(() =>
191 effect(() => {
192 expect(fromMyDataArrayKeyQueryFn.data()).toBe(142)
193 }),
194 )
195​
196 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
197 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
198 return Number(context.queryKey[0]) + 42
199 }
200​
201 const fromGetMyDataStringKeyQueryFn = TestBed.runInInjectionContext(() =>
202 injectQuery(() => ({
203 queryKey: ['1'] as ['1'],
204 queryFn: getMyDataStringKey,
205 })),
206 )
207 expectTypeOf(fromGetMyDataStringKeyQueryFn.data()).toEqualTypeOf<
208 number | undefined
209 >()
210​
211 TestBed.runInInjectionContext(() =>
212 effect(() => {
213 expect(fromGetMyDataStringKeyQueryFn.data()).toBe(43)
214 }),
215 )
216​
217 // handles wrapped queries with custom fetcher passed as inline queryFn
218 const createWrappedQuery = <
219 TQueryKey extends [string, Record<string, unknown>?],
220 TQueryFnData,
221 TError,
222 TData = TQueryFnData,
223 >(
224 qk: TQueryKey,
225 fetcher: (
226 obj: TQueryKey[1],
227 token: string,
228 // return type must be wrapped with TQueryFnReturn
229 ) => Promise<TQueryFnData>,
230 options?: OmitKeyof<
231 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
232 'queryKey' | 'queryFn' | 'initialData',
233 'safely'
234 >,
235 ) =>
236 injectQuery(() => ({
237 queryKey: qk,
238 queryFn: () => fetcher(qk[1], 'token'),
239 ...options,
240 }))
241 const fromWrappedQuery = TestBed.runInInjectionContext(() =>
242 createWrappedQuery([''], () => Promise.resolve('1')),
243 )
244 expectTypeOf(fromWrappedQuery.data()).toEqualTypeOf<string | undefined>()
245​
246 // handles wrapped queries with custom fetcher passed directly to createQuery
247 const createWrappedFuncStyleQuery = <
248 TQueryKey extends [string, Record<string, unknown>?],
249 TQueryFnData,
250 TError,
251 TData = TQueryFnData,
252 >(
253 qk: TQueryKey,
254 fetcher: () => Promise<TQueryFnData>,
255 options?: OmitKeyof<
256 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
257 'queryKey' | 'queryFn' | 'initialData',
258 'safely'
259 >,
260 ) => injectQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
261 const fromWrappedFuncStyleQuery = TestBed.runInInjectionContext(() =>
262 createWrappedFuncStyleQuery([''], () => Promise.resolve(true)),
263 )
264 expectTypeOf(fromWrappedFuncStyleQuery.data()).toEqualTypeOf<
265 boolean | undefined
266 >()
267 })
268​
269 test('should return pending status initially', () => {
270 const key = queryKey()
271 const query = TestBed.runInInjectionContext(() => {
272 return injectQuery(() => ({
273 queryKey: key,
274 queryFn: () => sleep(10).then(() => 'Some data'),
275 }))
276 })
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 const key = queryKey()
287 const query = TestBed.runInInjectionContext(() => {
288 return injectQuery(() => ({
289 queryKey: key,
290 queryFn: () => sleep(10).then(() => 'result2'),
291 }))
292 })
293​
294 await vi.advanceTimersByTimeAsync(11)
295 expect(query.status()).toBe('success')
296 expect(query.data()).toBe('result2')
297 expect(query.isPending()).toBe(false)
298 expect(query.isFetching()).toBe(false)
299 expect(query.isFetched()).toBe(true)
300 expect(query.isSuccess()).toBe(true)
301 })
302​
303 test('should reject and update signal', async () => {
304 const key = queryKey()
305 const query = TestBed.runInInjectionContext(() => {
306 return injectQuery(() => ({
307 retry: false,
308 queryKey: key,
309 queryFn: () =>
310 sleep(10).then(() => Promise.reject(new Error('Some error'))),
311 }))
312 })
313​
314 await vi.advanceTimersByTimeAsync(11)
315 expect(query.status()).toBe('error')
316 expect(query.data()).toBe(undefined)
317 expect(query.error()).toMatchObject({ message: 'Some error' })
318 expect(query.isPending()).toBe(false)
319 expect(query.isFetching()).toBe(false)
320 expect(query.isError()).toBe(true)
321 expect(query.failureCount()).toBe(1)
322 expect(query.failureReason()).toMatchObject({ message: 'Some error' })
323 })
324​
325 test('should update query on options contained signal change', async () => {
326 const key1 = queryKey()
327 const key2 = queryKey()
328 const key = signal(key1)
329 const spy = vi.fn(() => sleep(10).then(() => 'Some data'))
330​
331 const query = TestBed.runInInjectionContext(() => {
332 return injectQuery(() => ({
333 queryKey: key(),
334 queryFn: spy,
335 }))
336 })
337​
338 await vi.advanceTimersByTimeAsync(0)
339 expect(spy).toHaveBeenCalledTimes(1)
340​
341 await vi.advanceTimersByTimeAsync(11)
342 expect(query.status()).toBe('success')
343​
344 key.set(key2)
345 TestBed.tick()
346​
347 expect(spy).toHaveBeenCalledTimes(2)
348 // should call queryFn with context containing the new queryKey
349 expect(spy).toBeCalledWith({
350 client: queryClient,
351 meta: undefined,
352 queryKey: key2,
353 signal: expect.anything(),
354 })
355 })
356​
357 test('should only run query once enabled signal is set to true', async () => {
358 const key = queryKey()
359 const spy = vi.fn(() => sleep(10).then(() => 'Some data'))
360 const enabled = signal(false)
361​
362 const query = TestBed.runInInjectionContext(() => {
363 return injectQuery(() => ({
364 queryKey: key,
365 queryFn: spy,
366 enabled: enabled(),
367 }))
368 })
369​
370 expect(spy).not.toHaveBeenCalled()
371 expect(query.status()).toBe('pending')
372​
373 enabled.set(true)
374​
375 await vi.advanceTimersByTimeAsync(11)
376 expect(spy).toHaveBeenCalledTimes(1)
377 expect(query.status()).toBe('success')
378 })
379​
380 test('should properly execute dependent queries', async () => {
381 const key1 = queryKey()
382 const key2 = queryKey()
383​
384 const query1 = TestBed.runInInjectionContext(() => {
385 return injectQuery(() => ({
386 queryKey: key1,
387 queryFn: () => sleep(10).then(() => 'Some data'),
388 }))
389 })
390​
391 const dependentQueryFn = vi
392 .fn()
393 .mockImplementation(() => sleep(1000).then(() => 'Some data'))
394​
395 const query2 = TestBed.runInInjectionContext(() => {
396 return injectQuery(
397 computed(() => ({
398 queryKey: key2,
399 queryFn: dependentQueryFn,
400 enabled: !!query1.data(),
401 })),
402 )
403 })
404​
405 expect(query1.data()).toStrictEqual(undefined)
406 expect(query2.fetchStatus()).toStrictEqual('idle')
407 expect(dependentQueryFn).not.toHaveBeenCalled()
408​
409 await vi.advanceTimersByTimeAsync(11)
410​
411 expect(query1.data()).toStrictEqual('Some data')
412 expect(query2.fetchStatus()).toStrictEqual('fetching')
413​
414 await vi.advanceTimersByTimeAsync(1002)
415​
416 expect(query2.fetchStatus()).toStrictEqual('idle')
417 expect(query2.status()).toStrictEqual('success')
418 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
419 expect(dependentQueryFn).toHaveBeenCalledWith(
420 expect.objectContaining({ queryKey: key2 }),
421 )
422 })
423​
424 test('should use the current value for the queryKey when refetch is called', async () => {
425 const key = queryKey()
426 const fetchFn = vi.fn(() => sleep(10).then(() => 'Some data'))
427 const keySignal = signal('key11')
428​
429 const query = TestBed.runInInjectionContext(() => {
430 return injectQuery(() => ({
431 queryKey: [...key, keySignal()],
432 queryFn: fetchFn,
433 enabled: false,
434 }))
435 })
436​
437 expect(fetchFn).not.toHaveBeenCalled()
438​
439 void query.refetch().then(() => {
440 expect(fetchFn).toHaveBeenCalledTimes(1)
441 expect(fetchFn).toHaveBeenCalledWith(
442 expect.objectContaining({
443 queryKey: [...key, 'key11'],
444 }),
445 )
446 })
447​
448 await vi.advanceTimersByTimeAsync(11)
449​
450 keySignal.set('key12')
451​
452 void query.refetch().then(() => {
453 expect(fetchFn).toHaveBeenCalledTimes(2)
454 expect(fetchFn).toHaveBeenCalledWith(
455 expect.objectContaining({
456 queryKey: [...key, 'key12'],
457 }),
458 )
459 })
460​
461 await vi.advanceTimersByTimeAsync(11)
462 })
463​
464 describe('throwOnError', () => {
465 test('should evaluate throwOnError when query is expected to throw', async () => {
466 const key = queryKey()
467 const boundaryFn = vi.fn()
468 TestBed.runInInjectionContext(() => {
469 return injectQuery(() => ({
470 queryKey: key,
471 queryFn: () =>
472 sleep(10).then(() => Promise.reject(new Error('Some error'))),
473 retry: false,
474 throwOnError: boundaryFn,
475 }))
476 })
477​
478 await vi.advanceTimersByTimeAsync(11)
479 expect(boundaryFn).toHaveBeenCalledTimes(1)
480 expect(boundaryFn).toHaveBeenCalledWith(
481 Error('Some error'),
482 expect.objectContaining({
483 state: expect.objectContaining({ status: 'error' }),
484 }),
485 )
486 })
487​
488 test('should throw when throwOnError is true', async () => {
489 const key = queryKey()
490 TestBed.runInInjectionContext(() => {
491 return injectQuery(() => ({
492 queryKey: key,
493 queryFn: () =>
494 sleep(0).then(() => Promise.reject(new Error('Some error'))),
495 throwOnError: true,
496 }))
497 })
498​
499 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
500 })
501​
502 test('should throw when throwOnError function returns true', async () => {
503 const key = queryKey()
504 TestBed.runInInjectionContext(() => {
505 return injectQuery(() => ({
506 queryKey: key,
507 queryFn: () =>
508 sleep(0).then(() => Promise.reject(new Error('Some error'))),
509 throwOnError: () => true,
510 }))
511 })
512​
513 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
514 })
515 })
516​
517 test('should set state to error when queryFn returns reject promise', async () => {
518 const key = queryKey()
519 const query = TestBed.runInInjectionContext(() => {
520 return injectQuery(() => ({
521 retry: false,
522 queryKey: key,
523 queryFn: () =>
524 sleep(10).then(() => Promise.reject(new Error('Some error'))),
525 }))
526 })
527​
528 expect(query.status()).toBe('pending')
529​
530 await vi.advanceTimersByTimeAsync(11)
531​
532 expect(query.status()).toBe('error')
533 })
534​
535 test('should render with required signal inputs', async () => {
536 @Component({
537 selector: 'app-fake',
538 template: `{{ query.data() }}`,
539 })
540 class FakeComponent {
541 name = input.required<string>()
542​
543 query = injectQuery(() => ({
544 queryKey: ['fake', this.name()],
545 queryFn: () => this.name(),
546 }))
547 }
548​
549 const fixture = TestBed.createComponent(FakeComponent)
550 setSignalInputs(fixture.componentInstance, {
551 name: 'signal-input-required-test',
552 })
553​
554 fixture.detectChanges()
555 await vi.advanceTimersByTimeAsync(0)
556​
557 expect(fixture.componentInstance.query.data()).toEqual(
558 'signal-input-required-test',
559 )
560 })
561​
562 describe('isRestoring', () => {
563 test('should not fetch for the duration of the restoring period when isRestoring is true', async () => {
564 const key = queryKey()
565 const queryFn = vi
566 .fn()
567 .mockImplementation(() => sleep(10).then(() => 'data'))
568​
569 TestBed.resetTestingModule()
570 TestBed.configureTestingModule({
571 providers: [
572 provideZonelessChangeDetection(),
573 provideTanStackQuery(queryClient),
574 provideIsRestoring(signal(true).asReadonly()),
575 ],
576 })
577​
578 const query = TestBed.runInInjectionContext(() =>
579 injectQuery(() => ({
580 queryKey: key,
581 queryFn,
582 })),
583 )
584​
585 await vi.advanceTimersByTimeAsync(0)
586 expect(query.status()).toBe('pending')
587 expect(query.fetchStatus()).toBe('idle')
588 expect(query.data()).toBeUndefined()
589 expect(queryFn).toHaveBeenCalledTimes(0)
590​
591 await vi.advanceTimersByTimeAsync(11)
592 expect(query.status()).toBe('pending')
593 expect(query.fetchStatus()).toBe('idle')
594 expect(query.data()).toBeUndefined()
595 expect(queryFn).toHaveBeenCalledTimes(0)
596 })
597 })
598​
599 describe('injection context', () => {
600 test('throws NG0203 with descriptive error outside injection context', () => {
601 const key = queryKey()
602 expect(() => {
603 injectQuery(() => ({
604 queryKey: key,
605 queryFn: () => sleep(0).then(() => 'Some data'),
606 }))
607 }).toThrow(/NG0203(.*?)injectQuery/)
608 })
609​
610 test('can be used outside injection context when passing an injector', () => {
611 const key = queryKey()
612 const query = injectQuery(
613 () => ({
614 queryKey: key,
615 queryFn: () => sleep(0).then(() => 'Some data'),
616 }),
617 {
618 injector: TestBed.inject(Injector),
619 },
620 )
621​
622 expect(query.status()).toBe('pending')
623 })
624​
625 test('should complete queries before whenStable() resolves', async () => {
626 const key = queryKey()
627 const app = TestBed.inject(ApplicationRef)
628​
629 const query = TestBed.runInInjectionContext(() =>
630 injectQuery(() => ({
631 queryKey: key,
632 queryFn: () => sleep(50).then(() => 'test data'),
633 })),
634 )
635​
636 expect(query.status()).toBe('pending')
637 expect(query.data()).toBeUndefined()
638​
639 const stablePromise = app.whenStable()
640 await vi.advanceTimersByTimeAsync(60)
641 await stablePromise
642​
643 expect(query.status()).toBe('success')
644 expect(query.data()).toBe('test data')
645 })
646​
647 test('should complete HttpClient-based queries before whenStable() resolves', async () => {
648 TestBed.resetTestingModule()
649 TestBed.configureTestingModule({
650 providers: [
651 provideZonelessChangeDetection(),
652 provideTanStackQuery(queryClient),
653 provideHttpClient(),
654 provideHttpClientTesting(),
655 ],
656 })
657​
658 const app = TestBed.inject(ApplicationRef)
659 const httpClient = TestBed.inject(HttpClient)
660 const httpTestingController = TestBed.inject(HttpTestingController)
661​
662 // Create a query using HttpClient
663 const key = queryKey()
664 const query = TestBed.runInInjectionContext(() =>
665 injectQuery(() => ({
666 queryKey: key,
667 queryFn: () =>
668 lastValueFrom(httpClient.get<{ message: string }>('/api/test')),
669 })),
670 )
671​
672 // Schedule the HTTP response
673 setTimeout(() => {
674 const req = httpTestingController.expectOne('/api/test')
675 req.flush({ message: 'http test data' })
676 }, 10)
677​
678 // Initial state
679 expect(query.status()).toBe('pending')
680​
681 // Advance timers and wait for Angular to be "stable"
682 const stablePromise = app.whenStable()
683 await vi.advanceTimersByTimeAsync(20)
684 await stablePromise
685​
686 // Query should be complete after whenStable() thanks to PendingTasks integration
687 expect(query.status()).toBe('success')
688 expect(query.data()).toEqual({ message: 'http test data' })
689​
690 httpTestingController.verify()
691 })
692​
693 test('should handle synchronous queryFn with staleTime', async () => {
694 TestBed.resetTestingModule()
695 TestBed.configureTestingModule({
696 providers: [
697 provideZonelessChangeDetection(),
698 provideTanStackQuery(queryClient),
699 ],
700 })
701​
702 const app = TestBed.inject(ApplicationRef)
703 let callCount = 0
704​
705 const key = queryKey()
706 const query = TestBed.runInInjectionContext(() =>
707 injectQuery(() => ({
708 queryKey: key,
709 staleTime: 1000,
710 queryFn: () => {
711 callCount++
712 return `sync-data-${callCount}`
713 },
714 })),
715 )
716​
717 // Synchronize pending effects
718 TestBed.tick()
719​
720 const stablePromise = app.whenStable()
721 await stablePromise
722​
723 expect(query.status()).toBe('success')
724 expect(query.data()).toBe('sync-data-1')
725 expect(callCount).toBe(1)
726​
727 await query.refetch()
728 await Promise.resolve()
729 await vi.runAllTimersAsync()
730 await app.whenStable()
731​
732 expect(query.status()).toBe('success')
733 expect(query.data()).toBe('sync-data-2')
734 expect(callCount).toBe(2)
735 })
736​
737 test('should handle enabled/disabled transitions with synchronous queryFn', async () => {
738 TestBed.resetTestingModule()
739 TestBed.configureTestingModule({
740 providers: [
741 provideZonelessChangeDetection(),
742 provideTanStackQuery(queryClient),
743 ],
744 })
745​
746 const app = TestBed.inject(ApplicationRef)
747 const enabledSignal = signal(false)
748 let callCount = 0
749​
750 const key = queryKey()
751 const query = TestBed.runInInjectionContext(() =>
752 injectQuery(() => ({
753 queryKey: key,
754 enabled: enabledSignal(),
755 queryFn: () => {
756 callCount++
757 return `sync-data-${callCount}`
758 },
759 })),
760 )
761​
762 // Initially disabled
763 TestBed.tick()
764 await app.whenStable()
765 expect(query.status()).toBe('pending')
766 expect(query.data()).toBeUndefined()
767 expect(callCount).toBe(0)
768​
769 // Enable the query
770 enabledSignal.set(true)
771 TestBed.tick()
772​
773 await app.whenStable()
774 expect(query.status()).toBe('success')
775 expect(query.data()).toBe('sync-data-1')
776 expect(callCount).toBe(1)
777 })
778​
779 test('should handle query invalidation with synchronous data', async () => {
780 TestBed.resetTestingModule()
781 TestBed.configureTestingModule({
782 providers: [
783 provideZonelessChangeDetection(),
784 provideTanStackQuery(queryClient),
785 ],
786 })
787​
788 const app = TestBed.inject(ApplicationRef)
789 const testKey = queryKey()
790 let callCount = 0
791​
792 const query = TestBed.runInInjectionContext(() =>
793 injectQuery(() => ({
794 queryKey: testKey,
795 queryFn: () => {
796 callCount++
797 return `sync-data-${callCount}`
798 },
799 })),
800 )
801​
802 // Synchronize pending effects
803 TestBed.tick()
804​
805 await app.whenStable()
806 expect(query.status()).toBe('success')
807 expect(query.data()).toBe('sync-data-1')
808 expect(callCount).toBe(1)
809​
810 // Invalidate the query
811 queryClient.invalidateQueries({ queryKey: testKey })
812 TestBed.tick()
813​
814 // Wait for the invalidation to trigger a refetch
815 await Promise.resolve()
816 await vi.advanceTimersByTimeAsync(10)
817 TestBed.tick()
818​
819 await app.whenStable()
820 expect(query.status()).toBe('success')
821 expect(query.data()).toBe('sync-data-2')
822 expect(callCount).toBe(2)
823 })
824 })
825})