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

inject-query.test.ts

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