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