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

inject-query.test.ts

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