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

inject-query.test.ts

647 lines18.3 KB

1import {
2 Component,
3 Injectable,
4 Injector,
5 computed,
6 effect,
7 inject,
8 input,
9 provideExperimentalZonelessChangeDetection,
10 signal,
11} from '@angular/core'
12import { TestBed } from '@angular/core/testing'
13import { afterEach, describe, expect, vi } from 'vitest'
14import { QueryCache, QueryClient, injectQuery, provideTanStackQuery } from '..'
15import {
16 delayedFetcher,
17 getSimpleFetcherWithReturnData,
18 queryKey,
19 rejectFetcher,
20 setSignalInputs,
21 simpleFetcher,
22} from './test-utils'
23import type { CreateQueryOptions, OmitKeyof, QueryFunction } from '..'
24​
25const QUERY_DURATION = 100
26​
27const resolveQueries = () => vi.advanceTimersByTimeAsync(QUERY_DURATION)
28​
29describe('injectQuery', () => {
30 let queryCache: QueryCache
31 let queryClient: QueryClient
32 beforeEach(() => {
33 vi.useFakeTimers()
34 queryCache = new QueryCache()
35 queryClient = new QueryClient({ queryCache })
36 TestBed.configureTestingModule({
37 providers: [
38 provideExperimentalZonelessChangeDetection(),
39 provideTanStackQuery(queryClient),
40 ],
41 })
42 })
43​
44 afterEach(() => {
45 vi.useRealTimers()
46 })
47​
48 test('should return the correct types', () => {
49 const key = queryKey()
50 // unspecified query function should default to unknown
51 const noQueryFn = TestBed.runInInjectionContext(() =>
52 injectQuery(() => ({
53 queryKey: key,
54 })),
55 )
56 expectTypeOf(noQueryFn.data()).toEqualTypeOf<unknown>()
57 expectTypeOf(noQueryFn.error()).toEqualTypeOf<Error | null>()
58​
59 // it should infer the result type from the query function
60 const fromQueryFn = TestBed.runInInjectionContext(() =>
61 injectQuery(() => ({
62 queryKey: key,
63 queryFn: () => 'test',
64 })),
65 )
66 expectTypeOf(fromQueryFn.data()).toEqualTypeOf<string | undefined>()
67 expectTypeOf(fromQueryFn.error()).toEqualTypeOf<Error | null>()
68​
69 // it should be possible to specify the result type
70 const withResult = TestBed.runInInjectionContext(() =>
71 injectQuery<string>(() => ({
72 queryKey: key,
73 queryFn: () => 'test',
74 })),
75 )
76 expectTypeOf(withResult.data()).toEqualTypeOf<string | undefined>()
77 expectTypeOf(withResult.error()).toEqualTypeOf<Error | null>()
78​
79 // it should be possible to specify the error type
80 type CustomErrorType = { message: string }
81 const withError = TestBed.runInInjectionContext(() =>
82 injectQuery<string, CustomErrorType>(() => ({
83 queryKey: key,
84 queryFn: () => 'test',
85 })),
86 )
87 expectTypeOf(withError.data()).toEqualTypeOf<string | undefined>()
88 expectTypeOf(withError.error()).toEqualTypeOf<CustomErrorType | null>()
89​
90 // it should infer the result type from the configuration
91 const withResultInfer = TestBed.runInInjectionContext(() =>
92 injectQuery(() => ({
93 queryKey: key,
94 queryFn: () => true,
95 })),
96 )
97 expectTypeOf(withResultInfer.data()).toEqualTypeOf<boolean | undefined>()
98 expectTypeOf(withResultInfer.error()).toEqualTypeOf<Error | null>()
99​
100 // it should be possible to specify a union type as result type
101 const unionTypeSync = TestBed.runInInjectionContext(() =>
102 injectQuery(() => ({
103 queryKey: key,
104 queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
105 })),
106 )
107 expectTypeOf(unionTypeSync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
108 const unionTypeAsync = TestBed.runInInjectionContext(() =>
109 injectQuery<'a' | 'b'>(() => ({
110 queryKey: key,
111 queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
112 })),
113 )
114 expectTypeOf(unionTypeAsync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
115​
116 // it should error when the query function result does not match with the specified type
117 TestBed.runInInjectionContext(() =>
118 // @ts-expect-error
119 injectQuery<number>(() => ({ queryKey: key, queryFn: () => 'test' })),
120 )
121​
122 // it should infer the result type from a generic query function
123 /**
124 *
125 */
126 function queryFn<T = string>(): Promise<T> {
127 return Promise.resolve({} as T)
128 }
129​
130 const fromGenericQueryFn = TestBed.runInInjectionContext(() =>
131 injectQuery(() => ({
132 queryKey: key,
133 queryFn: () => queryFn(),
134 })),
135 )
136 expectTypeOf(fromGenericQueryFn.data()).toEqualTypeOf<string | undefined>()
137 expectTypeOf(fromGenericQueryFn.error()).toEqualTypeOf<Error | null>()
138​
139 // todo use query options?
140 const fromGenericOptionsQueryFn = TestBed.runInInjectionContext(() =>
141 injectQuery(() => ({
142 queryKey: key,
143 queryFn: () => queryFn(),
144 })),
145 )
146 expectTypeOf(fromGenericOptionsQueryFn.data()).toEqualTypeOf<
147 string | undefined
148 >()
149 expectTypeOf(
150 fromGenericOptionsQueryFn.error(),
151 ).toEqualTypeOf<Error | null>()
152​
153 type MyData = number
154 type MyQueryKey = readonly ['my-data', number]
155​
156 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
157 queryKey: [, n],
158 }) => {
159 return n + 42
160 }
161​
162 const fromMyDataArrayKeyQueryFn = TestBed.runInInjectionContext(() =>
163 injectQuery(() => ({
164 queryKey: ['my-data', 100] as const,
165 queryFn: getMyDataArrayKey,
166 })),
167 )
168 expectTypeOf(fromMyDataArrayKeyQueryFn.data()).toEqualTypeOf<
169 number | undefined
170 >()
171​
172 // it should handle query-functions that return Promise<any>
173 const fromPromiseAnyQueryFn = TestBed.runInInjectionContext(() =>
174 injectQuery(() => ({
175 queryKey: key,
176 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
177 })),
178 )
179 expectTypeOf(fromPromiseAnyQueryFn.data()).toEqualTypeOf<any | undefined>()
180​
181 TestBed.runInInjectionContext(() =>
182 effect(() => {
183 if (fromPromiseAnyQueryFn.isSuccess()) {
184 expect(fromMyDataArrayKeyQueryFn.data()).toBe(142)
185 }
186 }),
187 )
188​
189 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
190 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
191 return Number(context.queryKey[0]) + 42
192 }
193​
194 const fromGetMyDataStringKeyQueryFn = TestBed.runInInjectionContext(() =>
195 injectQuery(() => ({
196 queryKey: ['1'] as ['1'],
197 queryFn: getMyDataStringKey,
198 })),
199 )
200 expectTypeOf(fromGetMyDataStringKeyQueryFn.data()).toEqualTypeOf<
201 number | undefined
202 >()
203​
204 TestBed.runInInjectionContext(() =>
205 effect(() => {
206 if (fromGetMyDataStringKeyQueryFn.isSuccess()) {
207 expect(fromGetMyDataStringKeyQueryFn.data()).toBe(43)
208 }
209 }),
210 )
211​
212 // handles wrapped queries with custom fetcher passed as inline queryFn
213 const createWrappedQuery = <
214 TQueryKey extends [string, Record<string, unknown>?],
215 TQueryFnData,
216 TError,
217 TData = TQueryFnData,
218 >(
219 qk: TQueryKey,
220 fetcher: (
221 obj: TQueryKey[1],
222 token: string,
223 // return type must be wrapped with TQueryFnReturn
224 ) => Promise<TQueryFnData>,
225 options?: OmitKeyof<
226 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
227 'queryKey' | 'queryFn' | 'initialData',
228 'safely'
229 >,
230 ) =>
231 injectQuery(() => ({
232 queryKey: qk,
233 queryFn: () => fetcher(qk[1], 'token'),
234 ...options,
235 }))
236 const fromWrappedQuery = TestBed.runInInjectionContext(() =>
237 createWrappedQuery([''], async () => '1'),
238 )
239 expectTypeOf(fromWrappedQuery.data()).toEqualTypeOf<string | undefined>()
240​
241 // handles wrapped queries with custom fetcher passed directly to createQuery
242 const createWrappedFuncStyleQuery = <
243 TQueryKey extends [string, Record<string, unknown>?],
244 TQueryFnData,
245 TError,
246 TData = TQueryFnData,
247 >(
248 qk: TQueryKey,
249 fetcher: () => Promise<TQueryFnData>,
250 options?: OmitKeyof<
251 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
252 'queryKey' | 'queryFn' | 'initialData',
253 'safely'
254 >,
255 ) => injectQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
256 const fromWrappedFuncStyleQuery = TestBed.runInInjectionContext(() =>
257 createWrappedFuncStyleQuery([''], async () => true),
258 )
259 expectTypeOf(fromWrappedFuncStyleQuery.data()).toEqualTypeOf<
260 boolean | undefined
261 >()
262 })
263​
264 test('should return pending status initially', () => {
265 const query = TestBed.runInInjectionContext(() => {
266 return injectQuery(() => ({
267 queryKey: ['key1'],
268 queryFn: simpleFetcher,
269 }))
270 })
271​
272 expect(query.status()).toBe('pending')
273 expect(query.isPending()).toBe(true)
274 expect(query.isFetching()).toBe(true)
275 expect(query.isStale()).toBe(true)
276 expect(query.isFetched()).toBe(false)
277 })
278​
279 test('should resolve to success and update signal: injectQuery()', async () => {
280 const query = TestBed.runInInjectionContext(() => {
281 return injectQuery(() => ({
282 queryKey: ['key2'],
283 queryFn: getSimpleFetcherWithReturnData('result2'),
284 }))
285 })
286​
287 await resolveQueries()
288​
289 expect(query.status()).toBe('success')
290 expect(query.data()).toBe('result2')
291 expect(query.isPending()).toBe(false)
292 expect(query.isFetching()).toBe(false)
293 expect(query.isFetched()).toBe(true)
294 expect(query.isSuccess()).toBe(true)
295 })
296​
297 test('should reject and update signal', async () => {
298 const query = TestBed.runInInjectionContext(() => {
299 return injectQuery(() => ({
300 retry: false,
301 queryKey: ['key3'],
302 queryFn: rejectFetcher,
303 }))
304 })
305​
306 await resolveQueries()
307​
308 expect(query.status()).toBe('error')
309 expect(query.data()).toBe(undefined)
310 expect(query.error()).toMatchObject({ message: 'Some error' })
311 expect(query.isPending()).toBe(false)
312 expect(query.isFetching()).toBe(false)
313 expect(query.isError()).toBe(true)
314 expect(query.failureCount()).toBe(1)
315 expect(query.failureReason()).toMatchObject({ message: 'Some error' })
316 })
317​
318 test('should update query on options contained signal change', async () => {
319 const key = signal(['key6', 'key7'])
320 const spy = vi.fn(simpleFetcher)
321​
322 const query = TestBed.runInInjectionContext(() => {
323 return injectQuery(() => ({
324 queryKey: key(),
325 queryFn: spy,
326 }))
327 })
328​
329 await resolveQueries()
330​
331 expect(spy).toHaveBeenCalledTimes(1)
332​
333 expect(query.status()).toBe('success')
334​
335 key.set(['key8'])
336 TestBed.flushEffects()
337​
338 expect(spy).toHaveBeenCalledTimes(2)
339 // should call queryFn with context containing the new queryKey
340 expect(spy).toBeCalledWith({
341 client: queryClient,
342 meta: undefined,
343 queryKey: ['key8'],
344 signal: expect.anything(),
345 })
346 })
347​
348 test('should only run query once enabled signal is set to true', async () => {
349 const spy = vi.fn(simpleFetcher)
350 const enabled = signal(false)
351​
352 const query = TestBed.runInInjectionContext(() => {
353 return injectQuery(() => ({
354 queryKey: ['key9'],
355 queryFn: spy,
356 enabled: enabled(),
357 }))
358 })
359​
360 expect(spy).not.toHaveBeenCalled()
361 expect(query.status()).toBe('pending')
362​
363 enabled.set(true)
364 await resolveQueries()
365 expect(spy).toHaveBeenCalledTimes(1)
366 expect(query.status()).toBe('success')
367 })
368​
369 test('should properly execute dependant queries', async () => {
370 const query1 = TestBed.runInInjectionContext(() => {
371 return injectQuery(() => ({
372 queryKey: ['dependant1'],
373 queryFn: simpleFetcher,
374 }))
375 })
376​
377 const dependentQueryFn = vi.fn().mockImplementation(delayedFetcher(1000))
378​
379 const query2 = TestBed.runInInjectionContext(() => {
380 return injectQuery(
381 computed(() => ({
382 queryKey: ['dependant2'],
383 queryFn: dependentQueryFn,
384 enabled: !!query1.data(),
385 })),
386 )
387 })
388​
389 expect(query1.data()).toStrictEqual(undefined)
390 expect(query2.fetchStatus()).toStrictEqual('idle')
391 expect(dependentQueryFn).not.toHaveBeenCalled()
392​
393 await resolveQueries()
394​
395 expect(query1.data()).toStrictEqual('Some data')
396 expect(query2.fetchStatus()).toStrictEqual('fetching')
397​
398 await vi.runAllTimersAsync()
399​
400 expect(query2.fetchStatus()).toStrictEqual('idle')
401 expect(query2.status()).toStrictEqual('success')
402 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
403 expect(dependentQueryFn).toHaveBeenCalledWith(
404 expect.objectContaining({ queryKey: ['dependant2'] }),
405 )
406 })
407​
408 test('should use the current value for the queryKey when refetch is called', async () => {
409 const fetchFn = vi.fn(simpleFetcher)
410 const keySignal = signal('key11')
411​
412 const query = TestBed.runInInjectionContext(() => {
413 return injectQuery(() => ({
414 queryKey: ['key10', keySignal()],
415 queryFn: fetchFn,
416 enabled: false,
417 }))
418 })
419​
420 expect(fetchFn).not.toHaveBeenCalled()
421​
422 query.refetch().then(() => {
423 expect(fetchFn).toHaveBeenCalledTimes(1)
424 expect(fetchFn).toHaveBeenCalledWith(
425 expect.objectContaining({
426 queryKey: ['key10', 'key11'],
427 }),
428 )
429 })
430​
431 await resolveQueries()
432​
433 keySignal.set('key12')
434​
435 TestBed.flushEffects()
436​
437 query.refetch().then(() => {
438 expect(fetchFn).toHaveBeenCalledTimes(2)
439 expect(fetchFn).toHaveBeenCalledWith(
440 expect.objectContaining({
441 queryKey: ['key10', 'key12'],
442 }),
443 )
444 })
445​
446 await resolveQueries()
447 })
448​
449 describe('throwOnError', () => {
450 test('should evaluate throwOnError when query is expected to throw', async () => {
451 const boundaryFn = vi.fn()
452 TestBed.runInInjectionContext(() => {
453 return injectQuery(() => ({
454 queryKey: ['key12'],
455 queryFn: rejectFetcher,
456 throwOnError: boundaryFn,
457 }))
458 })
459​
460 await vi.runAllTimersAsync()
461​
462 expect(boundaryFn).toHaveBeenCalledTimes(1)
463 expect(boundaryFn).toHaveBeenCalledWith(
464 Error('Some error'),
465 expect.objectContaining({
466 state: expect.objectContaining({ status: 'error' }),
467 }),
468 )
469 })
470​
471 test('should throw when throwOnError is true', async () => {
472 TestBed.runInInjectionContext(() => {
473 return injectQuery(() => ({
474 queryKey: ['key13'],
475 queryFn: rejectFetcher,
476 throwOnError: true,
477 }))
478 })
479​
480 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
481 })
482​
483 test('should throw when throwOnError function returns true', async () => {
484 TestBed.runInInjectionContext(() => {
485 return injectQuery(() => ({
486 queryKey: ['key14'],
487 queryFn: rejectFetcher,
488 throwOnError: () => true,
489 }))
490 })
491​
492 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
493 })
494 })
495​
496 test('should set state to error when queryFn returns reject promise', async () => {
497 const query = TestBed.runInInjectionContext(() => {
498 return injectQuery(() => ({
499 retry: false,
500 queryKey: ['key15'],
501 queryFn: rejectFetcher,
502 }))
503 })
504​
505 expect(query.status()).toBe('pending')
506​
507 await resolveQueries()
508​
509 expect(query.status()).toBe('error')
510 })
511​
512 test('should render with required signal inputs', async () => {
513 @Component({
514 selector: 'app-fake',
515 template: `{{ query.data() }}`,
516 standalone: true,
517 })
518 class FakeComponent {
519 name = input.required<string>()
520​
521 query = injectQuery(() => ({
522 queryKey: ['fake', this.name()],
523 queryFn: () => this.name(),
524 }))
525 }
526​
527 const fixture = TestBed.createComponent(FakeComponent)
528 setSignalInputs(fixture.componentInstance, {
529 name: 'signal-input-required-test',
530 })
531​
532 fixture.detectChanges()
533 await resolveQueries()
534​
535 expect(fixture.componentInstance.query.data()).toEqual(
536 'signal-input-required-test',
537 )
538 })
539​
540 test('should run optionsFn in injection context', async () => {
541 @Injectable()
542 class FakeService {
543 getData(name: string) {
544 return Promise.resolve(name)
545 }
546 }
547​
548 @Component({
549 selector: 'app-fake',
550 template: `{{ query.data() }}`,
551 standalone: true,
552 providers: [FakeService],
553 })
554 class FakeComponent {
555 name = signal<string>('test name')
556​
557 query = injectQuery(() => {
558 const service = inject(FakeService)
559​
560 return {
561 queryKey: ['fake', this.name()],
562 queryFn: () => {
563 return service.getData(this.name())
564 },
565 }
566 })
567 }
568​
569 const fixture = TestBed.createComponent(FakeComponent)
570 fixture.detectChanges()
571 await resolveQueries()
572​
573 expect(fixture.componentInstance.query.data()).toEqual('test name')
574​
575 fixture.componentInstance.name.set('test name 2')
576 fixture.detectChanges()
577 await resolveQueries()
578​
579 expect(fixture.componentInstance.query.data()).toEqual('test name 2')
580 })
581​
582 test('should run optionsFn in injection context and allow passing injector to queryFn', async () => {
583 @Injectable()
584 class FakeService {
585 getData(name: string) {
586 return Promise.resolve(name)
587 }
588 }
589​
590 @Component({
591 selector: 'app-fake',
592 template: `{{ query.data() }}`,
593 standalone: true,
594 providers: [FakeService],
595 })
596 class FakeComponent {
597 name = signal<string>('test name')
598​
599 query = injectQuery(() => {
600 const injector = inject(Injector)
601​
602 return {
603 queryKey: ['fake', this.name()],
604 queryFn: () => {
605 const service = injector.get(FakeService)
606 return service.getData(this.name())
607 },
608 }
609 })
610 }
611​
612 const fixture = TestBed.createComponent(FakeComponent)
613 fixture.detectChanges()
614 await resolveQueries()
615​
616 expect(fixture.componentInstance.query.data()).toEqual('test name')
617​
618 fixture.componentInstance.name.set('test name 2')
619 fixture.detectChanges()
620 await resolveQueries()
621​
622 expect(fixture.componentInstance.query.data()).toEqual('test name 2')
623 })
624​
625 describe('injection context', () => {
626 test('throws NG0203 with descriptive error outside injection context', () => {
627 expect(() => {
628 injectQuery(() => ({
629 queryKey: ['injectionContextError'],
630 queryFn: simpleFetcher,
631 }))
632 }).toThrowError(/NG0203(.*?)injectQuery/)
633 })
634​
635 test('can be used outside injection context when passing an injector', () => {
636 const query = injectQuery(
637 () => ({
638 queryKey: ['manualInjector'],
639 queryFn: simpleFetcher,
640 }),
641 TestBed.inject(Injector),
642 )
643​
644 expect(query.status()).toBe('pending')
645 })
646 })
647})