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

inject-query.test.ts

635 lines17.8 KB

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