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

inject-query.test.ts

864 lines25.7 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 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).toHaveBeenNthCalledWith(2, {
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).toHaveBeenNthCalledWith(
532 1,
533 expect.objectContaining({
534 queryKey: [...key, 'key11'],
535 }),
536 )
537 })
538​
539 await vi.advanceTimersByTimeAsync(11)
540​
541 keySignal.set('key12')
542​
543 void query.refetch().then(() => {
544 expect(fetchFn).toHaveBeenCalledTimes(2)
545 expect(fetchFn).toHaveBeenNthCalledWith(
546 2,
547 expect.objectContaining({
548 queryKey: [...key, 'key12'],
549 }),
550 )
551 })
552​
553 await vi.advanceTimersByTimeAsync(11)
554 })
555​
556 describe('throwOnError', () => {
557 it('should evaluate throwOnError when query is expected to throw', async () => {
558 const key = queryKey()
559 const boundaryFn = vi.fn()
560 TestBed.runInInjectionContext(() => {
561 return injectQuery(() => ({
562 queryKey: key,
563 queryFn: () =>
564 sleep(10).then(() => Promise.reject(new Error('Some error'))),
565 retry: false,
566 throwOnError: boundaryFn,
567 }))
568 })
569​
570 await vi.advanceTimersByTimeAsync(11)
571 expect(boundaryFn).toHaveBeenCalledTimes(1)
572 expect(boundaryFn).toHaveBeenCalledWith(
573 Error('Some error'),
574 expect.objectContaining({
575 state: expect.objectContaining({ status: 'error' }),
576 }),
577 )
578 })
579​
580 it('should throw when throwOnError is true', async () => {
581 const key = queryKey()
582 TestBed.runInInjectionContext(() => {
583 return injectQuery(() => ({
584 queryKey: key,
585 queryFn: () =>
586 sleep(0).then(() => Promise.reject(new Error('Some error'))),
587 throwOnError: true,
588 }))
589 })
590​
591 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
592 })
593​
594 it('should throw when throwOnError function returns true', async () => {
595 const key = queryKey()
596 TestBed.runInInjectionContext(() => {
597 return injectQuery(() => ({
598 queryKey: key,
599 queryFn: () =>
600 sleep(0).then(() => Promise.reject(new Error('Some error'))),
601 throwOnError: () => true,
602 }))
603 })
604​
605 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
606 })
607 })
608​
609 it('should render with required signal inputs', async () => {
610 @Component({
611 selector: 'app-fake',
612 template: `{{ query.data() }}`,
613 })
614 class FakeComponent {
615 name = input.required<string>()
616​
617 query = injectQuery(() => ({
618 queryKey: ['fake', this.name()],
619 queryFn: () => this.name(),
620 }))
621 }
622​
623 const fixture = TestBed.createComponent(FakeComponent)
624 setSignalInputs(fixture.componentInstance, {
625 name: 'signal-input-required-test',
626 })
627​
628 fixture.detectChanges()
629 await vi.advanceTimersByTimeAsync(0)
630​
631 expect(fixture.componentInstance.query.data()).toEqual(
632 'signal-input-required-test',
633 )
634 })
635​
636 describe('isRestoring', () => {
637 it('should not fetch for the duration of the restoring period when isRestoring is true', async () => {
638 const key = queryKey()
639 const queryFn = vi
640 .fn()
641 .mockImplementation(() => sleep(10).then(() => 'data'))
642​
643 TestBed.configureTestingModule({
644 providers: [provideIsRestoring(signal(true).asReadonly())],
645 })
646​
647 const query = TestBed.runInInjectionContext(() =>
648 injectQuery(() => ({
649 queryKey: key,
650 queryFn,
651 })),
652 )
653​
654 await vi.advanceTimersByTimeAsync(0)
655 expect(query.status()).toBe('pending')
656 expect(query.fetchStatus()).toBe('idle')
657 expect(query.data()).toBeUndefined()
658 expect(queryFn).toHaveBeenCalledTimes(0)
659​
660 await vi.advanceTimersByTimeAsync(11)
661 expect(query.status()).toBe('pending')
662 expect(query.fetchStatus()).toBe('idle')
663 expect(query.data()).toBeUndefined()
664 expect(queryFn).toHaveBeenCalledTimes(0)
665 })
666 })
667​
668 describe('injection context', () => {
669 it('should throw NG0203 with descriptive error outside injection context', () => {
670 const key = queryKey()
671 expect(() => {
672 injectQuery(() => ({
673 queryKey: key,
674 queryFn: () => sleep(0).then(() => 'Some data'),
675 }))
676 }).toThrow(/NG0203(.*?)injectQuery/)
677 })
678​
679 it('should be usable outside injection context when passing an injector', () => {
680 const key = queryKey()
681 const query = injectQuery(
682 () => ({
683 queryKey: key,
684 queryFn: () => sleep(0).then(() => 'Some data'),
685 }),
686 {
687 injector: TestBed.inject(Injector),
688 },
689 )
690​
691 expect(query.status()).toBe('pending')
692 })
693​
694 it('should complete queries before whenStable() resolves', async () => {
695 const key = queryKey()
696 const app = TestBed.inject(ApplicationRef)
697​
698 const query = TestBed.runInInjectionContext(() =>
699 injectQuery(() => ({
700 queryKey: key,
701 queryFn: () => sleep(50).then(() => 'test data'),
702 })),
703 )
704​
705 expect(query.status()).toBe('pending')
706 expect(query.data()).toBeUndefined()
707​
708 const stablePromise = app.whenStable()
709 await vi.advanceTimersByTimeAsync(60)
710 await stablePromise
711​
712 expect(query.status()).toBe('success')
713 expect(query.data()).toBe('test data')
714 })
715​
716 it('should complete HttpClient-based queries before whenStable() resolves', async () => {
717 TestBed.configureTestingModule({
718 providers: [provideHttpClient(), provideHttpClientTesting()],
719 })
720​
721 const app = TestBed.inject(ApplicationRef)
722 const httpClient = TestBed.inject(HttpClient)
723 const httpTestingController = TestBed.inject(HttpTestingController)
724​
725 // Create a query using HttpClient
726 const key = queryKey()
727 const query = TestBed.runInInjectionContext(() =>
728 injectQuery(() => ({
729 queryKey: key,
730 queryFn: () =>
731 lastValueFrom(httpClient.get<{ message: string }>('/api/test')),
732 })),
733 )
734​
735 // Schedule the HTTP response
736 setTimeout(() => {
737 const req = httpTestingController.expectOne('/api/test')
738 req.flush({ message: 'http test data' })
739 }, 10)
740​
741 // Initial state
742 expect(query.status()).toBe('pending')
743​
744 // Advance timers and wait for Angular to be "stable"
745 const stablePromise = app.whenStable()
746 await vi.advanceTimersByTimeAsync(20)
747 await stablePromise
748​
749 // Query should be complete after whenStable() thanks to PendingTasks integration
750 expect(query.status()).toBe('success')
751 expect(query.data()).toEqual({ message: 'http test data' })
752​
753 httpTestingController.verify()
754 })
755​
756 it('should handle synchronous queryFn with staleTime', async () => {
757 const app = TestBed.inject(ApplicationRef)
758 let callCount = 0
759​
760 const key = queryKey()
761 const query = TestBed.runInInjectionContext(() =>
762 injectQuery(() => ({
763 queryKey: key,
764 staleTime: 1000,
765 queryFn: () => {
766 callCount++
767 return `sync-data-${callCount}`
768 },
769 })),
770 )
771​
772 // Synchronize pending effects
773 TestBed.tick()
774​
775 const stablePromise = app.whenStable()
776 await stablePromise
777​
778 expect(query.status()).toBe('success')
779 expect(query.data()).toBe('sync-data-1')
780 expect(callCount).toBe(1)
781​
782 await query.refetch()
783 await Promise.resolve()
784 await vi.runAllTimersAsync()
785 await app.whenStable()
786​
787 expect(query.status()).toBe('success')
788 expect(query.data()).toBe('sync-data-2')
789 expect(callCount).toBe(2)
790 })
791​
792 it('should handle enabled/disabled transitions with synchronous queryFn', async () => {
793 const app = TestBed.inject(ApplicationRef)
794 const enabledSignal = signal(false)
795 let callCount = 0
796​
797 const key = queryKey()
798 const query = TestBed.runInInjectionContext(() =>
799 injectQuery(() => ({
800 queryKey: key,
801 enabled: enabledSignal(),
802 queryFn: () => {
803 callCount++
804 return `sync-data-${callCount}`
805 },
806 })),
807 )
808​
809 // Initially disabled
810 TestBed.tick()
811 await app.whenStable()
812 expect(query.status()).toBe('pending')
813 expect(query.data()).toBeUndefined()
814 expect(callCount).toBe(0)
815​
816 // Enable the query
817 enabledSignal.set(true)
818 TestBed.tick()
819​
820 await app.whenStable()
821 expect(query.status()).toBe('success')
822 expect(query.data()).toBe('sync-data-1')
823 expect(callCount).toBe(1)
824 })
825​
826 it('should handle query invalidation with synchronous data', async () => {
827 const app = TestBed.inject(ApplicationRef)
828 const testKey = queryKey()
829 let callCount = 0
830​
831 const query = TestBed.runInInjectionContext(() =>
832 injectQuery(() => ({
833 queryKey: testKey,
834 queryFn: () => {
835 callCount++
836 return `sync-data-${callCount}`
837 },
838 })),
839 )
840​
841 // Synchronize pending effects
842 TestBed.tick()
843​
844 await app.whenStable()
845 expect(query.status()).toBe('success')
846 expect(query.data()).toBe('sync-data-1')
847 expect(callCount).toBe(1)
848​
849 // Invalidate the query
850 queryClient.invalidateQueries({ queryKey: testKey })
851 TestBed.tick()
852​
853 // Wait for the invalidation to trigger a refetch
854 await Promise.resolve()
855 await vi.advanceTimersByTimeAsync(10)
856 TestBed.tick()
857​
858 await app.whenStable()
859 expect(query.status()).toBe('success')
860 expect(query.data()).toBe('sync-data-2')
861 expect(callCount).toBe(2)
862 })
863 })
864})