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 be able to select a part of the data with select', async () => {
360 const key = queryKey()
361
362 @Component({
363 template: `<div>data: {{ query.data() ?? 'none' }}</div>`,
364 })
365 class Page {
366 readonly query = injectQuery<{ name: string }, Error, string>(() => ({
367 queryKey: key,
368 queryFn: () => sleep(10).then(() => ({ name: 'test' })),
369 select: (data) => data.name,
370 }))
371 }
372
373 const rendered = await render(Page)
374
375 expect(rendered.getByText('data: none')).toBeInTheDocument()
376
377 await vi.advanceTimersByTimeAsync(11)
378 rendered.fixture.detectChanges()
379
380 expect(rendered.getByText('data: test')).toBeInTheDocument()
381 })
382
383 it('should show placeholderData until queryFn resolves and then expose real data', async () => {
384 const key = queryKey()
385
386 @Component({
387 template: `
388 <div>data: {{ query.data() }}</div>
389 <div>isPlaceholderData: {{ query.isPlaceholderData() }}</div>
390 <div>isSuccess: {{ query.isSuccess() }}</div>
391 `,
392 })
393 class Page {
394 readonly query = injectQuery(() => ({
395 queryKey: key,
396 queryFn: () => sleep(10).then(() => 'real-data'),
397 placeholderData: 'placeholder',
398 }))
399 }
400
401 const rendered = await render(Page)
402
403 expect(rendered.getByText('data: placeholder')).toBeInTheDocument()
404 expect(rendered.getByText('isPlaceholderData: true')).toBeInTheDocument()
405 expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
406
407 await vi.advanceTimersByTimeAsync(11)
408 rendered.fixture.detectChanges()
409
410 expect(rendered.getByText('data: real-data')).toBeInTheDocument()
411 expect(rendered.getByText('isPlaceholderData: false')).toBeInTheDocument()
412 expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
413 })
414
415 it('should update query on options contained signal change', async () => {
416 const key1 = queryKey()
417 const key2 = queryKey()
418 const key = signal(key1)
419 const spy = vi.fn(() => sleep(10).then(() => 'Some data'))
420
421 const query = TestBed.runInInjectionContext(() => {
422 return injectQuery(() => ({
423 queryKey: key(),
424 queryFn: spy,
425 }))
426 })
427
428 await vi.advanceTimersByTimeAsync(0)
429 expect(spy).toHaveBeenCalledTimes(1)
430
431 await vi.advanceTimersByTimeAsync(11)
432 expect(query.status()).toBe('success')
433
434 key.set(key2)
435 TestBed.tick()
436
437 expect(spy).toHaveBeenCalledTimes(2)
438 // should call queryFn with context containing the new queryKey
439 expect(spy).toHaveBeenCalledWith({
440 client: queryClient,
441 meta: undefined,
442 queryKey: key2,
443 signal: expect.anything(),
444 })
445 })
446
447 it('should only run query once enabled signal is set to true', async () => {
448 const key = queryKey()
449 const spy = vi.fn(() => sleep(10).then(() => 'Some data'))
450 const enabled = signal(false)
451
452 const query = TestBed.runInInjectionContext(() => {
453 return injectQuery(() => ({
454 queryKey: key,
455 queryFn: spy,
456 enabled: enabled(),
457 }))
458 })
459
460 expect(spy).not.toHaveBeenCalled()
461 expect(query.status()).toBe('pending')
462
463 enabled.set(true)
464
465 await vi.advanceTimersByTimeAsync(11)
466 expect(spy).toHaveBeenCalledTimes(1)
467 expect(query.status()).toBe('success')
468 })
469
470 it('should properly execute dependent queries', async () => {
471 const key1 = queryKey()
472 const key2 = queryKey()
473
474 const query1 = TestBed.runInInjectionContext(() => {
475 return injectQuery(() => ({
476 queryKey: key1,
477 queryFn: () => sleep(10).then(() => 'Some data'),
478 }))
479 })
480
481 const dependentQueryFn = vi
482 .fn()
483 .mockImplementation(() => sleep(1000).then(() => 'Some data'))
484
485 const query2 = TestBed.runInInjectionContext(() => {
486 return injectQuery(
487 computed(() => ({
488 queryKey: key2,
489 queryFn: dependentQueryFn,
490 enabled: !!query1.data(),
491 })),
492 )
493 })
494
495 expect(query1.data()).toStrictEqual(undefined)
496 expect(query2.fetchStatus()).toStrictEqual('idle')
497 expect(dependentQueryFn).not.toHaveBeenCalled()
498
499 await vi.advanceTimersByTimeAsync(11)
500
501 expect(query1.data()).toStrictEqual('Some data')
502 expect(query2.fetchStatus()).toStrictEqual('fetching')
503
504 await vi.advanceTimersByTimeAsync(1002)
505
506 expect(query2.fetchStatus()).toStrictEqual('idle')
507 expect(query2.status()).toStrictEqual('success')
508 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
509 expect(dependentQueryFn).toHaveBeenCalledWith(
510 expect.objectContaining({ queryKey: key2 }),
511 )
512 })
513
514 it('should use the current value for the queryKey when refetch is called', async () => {
515 const key = queryKey()
516 const fetchFn = vi.fn(() => sleep(10).then(() => 'Some data'))
517 const keySignal = signal('key11')
518
519 const query = TestBed.runInInjectionContext(() => {
520 return injectQuery(() => ({
521 queryKey: [...key, keySignal()],
522 queryFn: fetchFn,
523 enabled: false,
524 }))
525 })
526
527 expect(fetchFn).not.toHaveBeenCalled()
528
529 void query.refetch().then(() => {
530 expect(fetchFn).toHaveBeenCalledTimes(1)
531 expect(fetchFn).toHaveBeenCalledWith(
532 expect.objectContaining({
533 queryKey: [...key, 'key11'],
534 }),
535 )
536 })
537
538 await vi.advanceTimersByTimeAsync(11)
539
540 keySignal.set('key12')
541
542 void query.refetch().then(() => {
543 expect(fetchFn).toHaveBeenCalledTimes(2)
544 expect(fetchFn).toHaveBeenCalledWith(
545 expect.objectContaining({
546 queryKey: [...key, 'key12'],
547 }),
548 )
549 })
550
551 await vi.advanceTimersByTimeAsync(11)
552 })
553
554 describe('throwOnError', () => {
555 it('should evaluate throwOnError when query is expected to throw', async () => {
556 const key = queryKey()
557 const boundaryFn = vi.fn()
558 TestBed.runInInjectionContext(() => {
559 return injectQuery(() => ({
560 queryKey: key,
561 queryFn: () =>
562 sleep(10).then(() => Promise.reject(new Error('Some error'))),
563 retry: false,
564 throwOnError: boundaryFn,
565 }))
566 })
567
568 await vi.advanceTimersByTimeAsync(11)
569 expect(boundaryFn).toHaveBeenCalledTimes(1)
570 expect(boundaryFn).toHaveBeenCalledWith(
571 Error('Some error'),
572 expect.objectContaining({
573 state: expect.objectContaining({ status: 'error' }),
574 }),
575 )
576 })
577
578 it('should throw when throwOnError is true', async () => {
579 const key = queryKey()
580 TestBed.runInInjectionContext(() => {
581 return injectQuery(() => ({
582 queryKey: key,
583 queryFn: () =>
584 sleep(0).then(() => Promise.reject(new Error('Some error'))),
585 throwOnError: true,
586 }))
587 })
588
589 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
590 })
591
592 it('should throw when throwOnError function returns true', async () => {
593 const key = queryKey()
594 TestBed.runInInjectionContext(() => {
595 return injectQuery(() => ({
596 queryKey: key,
597 queryFn: () =>
598 sleep(0).then(() => Promise.reject(new Error('Some error'))),
599 throwOnError: () => true,
600 }))
601 })
602
603 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
604 })
605 })
606
607 it('should render with required signal inputs', async () => {
608 @Component({
609 selector: 'app-fake',
610 template: `{{ query.data() }}`,
611 })
612 class FakeComponent {
613 name = input.required<string>()
614
615 query = injectQuery(() => ({
616 queryKey: ['fake', this.name()],
617 queryFn: () => this.name(),
618 }))
619 }
620
621 const fixture = TestBed.createComponent(FakeComponent)
622 setSignalInputs(fixture.componentInstance, {
623 name: 'signal-input-required-test',
624 })
625
626 fixture.detectChanges()
627 await vi.advanceTimersByTimeAsync(0)
628
629 expect(fixture.componentInstance.query.data()).toEqual(
630 'signal-input-required-test',
631 )
632 })
633
634 describe('isRestoring', () => {
635 it('should not fetch for the duration of the restoring period when isRestoring is true', async () => {
636 const key = queryKey()
637 const queryFn = vi
638 .fn()
639 .mockImplementation(() => sleep(10).then(() => 'data'))
640
641 TestBed.configureTestingModule({
642 providers: [provideIsRestoring(signal(true).asReadonly())],
643 })
644
645 const query = TestBed.runInInjectionContext(() =>
646 injectQuery(() => ({
647 queryKey: key,
648 queryFn,
649 })),
650 )
651
652 await vi.advanceTimersByTimeAsync(0)
653 expect(query.status()).toBe('pending')
654 expect(query.fetchStatus()).toBe('idle')
655 expect(query.data()).toBeUndefined()
656 expect(queryFn).toHaveBeenCalledTimes(0)
657
658 await vi.advanceTimersByTimeAsync(11)
659 expect(query.status()).toBe('pending')
660 expect(query.fetchStatus()).toBe('idle')
661 expect(query.data()).toBeUndefined()
662 expect(queryFn).toHaveBeenCalledTimes(0)
663 })
664 })
665
666 describe('injection context', () => {
667 it('should throw NG0203 with descriptive error outside injection context', () => {
668 const key = queryKey()
669 expect(() => {
670 injectQuery(() => ({
671 queryKey: key,
672 queryFn: () => sleep(0).then(() => 'Some data'),
673 }))
674 }).toThrow(/NG0203(.*?)injectQuery/)
675 })
676
677 it('should be usable outside injection context when passing an injector', () => {
678 const key = queryKey()
679 const query = injectQuery(
680 () => ({
681 queryKey: key,
682 queryFn: () => sleep(0).then(() => 'Some data'),
683 }),
684 {
685 injector: TestBed.inject(Injector),
686 },
687 )
688
689 expect(query.status()).toBe('pending')
690 })
691
692 it('should complete queries before whenStable() resolves', async () => {
693 const key = queryKey()
694 const app = TestBed.inject(ApplicationRef)
695
696 const query = TestBed.runInInjectionContext(() =>
697 injectQuery(() => ({
698 queryKey: key,
699 queryFn: () => sleep(50).then(() => 'test data'),
700 })),
701 )
702
703 expect(query.status()).toBe('pending')
704 expect(query.data()).toBeUndefined()
705
706 const stablePromise = app.whenStable()
707 await vi.advanceTimersByTimeAsync(60)
708 await stablePromise
709
710 expect(query.status()).toBe('success')
711 expect(query.data()).toBe('test data')
712 })
713
714 it('should complete HttpClient-based queries before whenStable() resolves', async () => {
715 TestBed.configureTestingModule({
716 providers: [provideHttpClient(), provideHttpClientTesting()],
717 })
718
719 const app = TestBed.inject(ApplicationRef)
720 const httpClient = TestBed.inject(HttpClient)
721 const httpTestingController = TestBed.inject(HttpTestingController)
722
723 // Create a query using HttpClient
724 const key = queryKey()
725 const query = TestBed.runInInjectionContext(() =>
726 injectQuery(() => ({
727 queryKey: key,
728 queryFn: () =>
729 lastValueFrom(httpClient.get<{ message: string }>('/api/test')),
730 })),
731 )
732
733 // Schedule the HTTP response
734 setTimeout(() => {
735 const req = httpTestingController.expectOne('/api/test')
736 req.flush({ message: 'http test data' })
737 }, 10)
738
739 // Initial state
740 expect(query.status()).toBe('pending')
741
742 // Advance timers and wait for Angular to be "stable"
743 const stablePromise = app.whenStable()
744 await vi.advanceTimersByTimeAsync(20)
745 await stablePromise
746
747 // Query should be complete after whenStable() thanks to PendingTasks integration
748 expect(query.status()).toBe('success')
749 expect(query.data()).toEqual({ message: 'http test data' })
750
751 httpTestingController.verify()
752 })
753
754 it('should handle synchronous queryFn with staleTime', async () => {
755 const app = TestBed.inject(ApplicationRef)
756 let callCount = 0
757
758 const key = queryKey()
759 const query = TestBed.runInInjectionContext(() =>
760 injectQuery(() => ({
761 queryKey: key,
762 staleTime: 1000,
763 queryFn: () => {
764 callCount++
765 return `sync-data-${callCount}`
766 },
767 })),
768 )
769
770 // Synchronize pending effects
771 TestBed.tick()
772
773 const stablePromise = app.whenStable()
774 await stablePromise
775
776 expect(query.status()).toBe('success')
777 expect(query.data()).toBe('sync-data-1')
778 expect(callCount).toBe(1)
779
780 await query.refetch()
781 await Promise.resolve()
782 await vi.runAllTimersAsync()
783 await app.whenStable()
784
785 expect(query.status()).toBe('success')
786 expect(query.data()).toBe('sync-data-2')
787 expect(callCount).toBe(2)
788 })
789
790 it('should handle enabled/disabled transitions with synchronous queryFn', async () => {
791 const app = TestBed.inject(ApplicationRef)
792 const enabledSignal = signal(false)
793 let callCount = 0
794
795 const key = queryKey()
796 const query = TestBed.runInInjectionContext(() =>
797 injectQuery(() => ({
798 queryKey: key,
799 enabled: enabledSignal(),
800 queryFn: () => {
801 callCount++
802 return `sync-data-${callCount}`
803 },
804 })),
805 )
806
807 // Initially disabled
808 TestBed.tick()
809 await app.whenStable()
810 expect(query.status()).toBe('pending')
811 expect(query.data()).toBeUndefined()
812 expect(callCount).toBe(0)
813
814 // Enable the query
815 enabledSignal.set(true)
816 TestBed.tick()
817
818 await app.whenStable()
819 expect(query.status()).toBe('success')
820 expect(query.data()).toBe('sync-data-1')
821 expect(callCount).toBe(1)
822 })
823
824 it('should handle query invalidation with synchronous data', async () => {
825 const app = TestBed.inject(ApplicationRef)
826 const testKey = queryKey()
827 let callCount = 0
828
829 const query = TestBed.runInInjectionContext(() =>
830 injectQuery(() => ({
831 queryKey: testKey,
832 queryFn: () => {
833 callCount++
834 return `sync-data-${callCount}`
835 },
836 })),
837 )
838
839 // Synchronize pending effects
840 TestBed.tick()
841
842 await app.whenStable()
843 expect(query.status()).toBe('success')
844 expect(query.data()).toBe('sync-data-1')
845 expect(callCount).toBe(1)
846
847 // Invalidate the query
848 queryClient.invalidateQueries({ queryKey: testKey })
849 TestBed.tick()
850
851 // Wait for the invalidation to trigger a refetch
852 await Promise.resolve()
853 await vi.advanceTimersByTimeAsync(10)
854 TestBed.tick()
855
856 await app.whenStable()
857 expect(query.status()).toBe('success')
858 expect(query.data()).toBe('sync-data-2')
859 expect(callCount).toBe(2)
860 })
861 })
862})