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

inject-query.test.ts

644 lines18.0 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: async () => 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 flush()
268 }))
269​
270 test('should resolve to success and update signal: injectQuery()', fakeAsync(() => {
271 const query = TestBed.runInInjectionContext(() => {
272 return injectQuery(() => ({
273 queryKey: ['key2'],
274 queryFn: getSimpleFetcherWithReturnData('result2'),
275 }))
276 })
277​
278 flush()
279​
280 expect(query.status()).toBe('success')
281 expect(query.data()).toBe('result2')
282 expect(query.isPending()).toBe(false)
283 expect(query.isFetching()).toBe(false)
284 expect(query.isFetched()).toBe(true)
285 expect(query.isSuccess()).toBe(true)
286 }))
287​
288 test('should reject and update signal', fakeAsync(() => {
289 const query = TestBed.runInInjectionContext(() => {
290 return injectQuery(() => ({
291 retry: false,
292 queryKey: ['key3'],
293 queryFn: rejectFetcher,
294 }))
295 })
296​
297 flush()
298​
299 expect(query.status()).toBe('error')
300 expect(query.data()).toBe(undefined)
301 expect(query.error()).toMatchObject({ message: 'Some error' })
302 expect(query.isPending()).toBe(false)
303 expect(query.isFetching()).toBe(false)
304 expect(query.isError()).toBe(true)
305 expect(query.failureCount()).toBe(1)
306 expect(query.failureReason()).toMatchObject({ message: 'Some error' })
307 }))
308​
309 test('should update query on options contained signal change', fakeAsync(() => {
310 const key = signal(['key6', 'key7'])
311 const spy = vi.fn(simpleFetcher)
312​
313 const query = TestBed.runInInjectionContext(() => {
314 return injectQuery(() => ({
315 queryKey: key(),
316 queryFn: spy,
317 }))
318 })
319 flush()
320 expect(spy).toHaveBeenCalledTimes(1)
321​
322 expect(query.status()).toBe('success')
323​
324 key.set(['key8'])
325 TestBed.flushEffects()
326​
327 expect(spy).toHaveBeenCalledTimes(2)
328 // should call queryFn with context containing the new queryKey
329 expect(spy).toBeCalledWith({
330 meta: undefined,
331 queryKey: ['key8'],
332 signal: expect.anything(),
333 })
334 flush()
335 }))
336​
337 test('should only run query once enabled signal is set to true', fakeAsync(() => {
338 const spy = vi.fn(simpleFetcher)
339 const enabled = signal(false)
340​
341 const query = TestBed.runInInjectionContext(() => {
342 return injectQuery(() => ({
343 queryKey: ['key9'],
344 queryFn: spy,
345 enabled: enabled(),
346 }))
347 })
348​
349 expect(spy).not.toHaveBeenCalled()
350 expect(query.status()).toBe('pending')
351​
352 enabled.set(true)
353 TestBed.flushEffects()
354 flush()
355 expect(spy).toHaveBeenCalledTimes(1)
356 expect(query.status()).toBe('success')
357 }))
358​
359 test('should properly execute dependant queries', fakeAsync(() => {
360 const query1 = TestBed.runInInjectionContext(() => {
361 return injectQuery(() => ({
362 queryKey: ['dependant1'],
363 queryFn: simpleFetcher,
364 }))
365 })
366​
367 const dependentQueryFn = vi.fn().mockImplementation(delayedFetcher(1000))
368​
369 const query2 = TestBed.runInInjectionContext(() => {
370 return injectQuery(
371 computed(() => ({
372 queryKey: ['dependant2'],
373 queryFn: dependentQueryFn,
374 enabled: !!query1.data(),
375 })),
376 )
377 })
378​
379 expect(query1.data()).toStrictEqual(undefined)
380 expect(query2.fetchStatus()).toStrictEqual('idle')
381 expect(dependentQueryFn).not.toHaveBeenCalled()
382​
383 tick()
384 TestBed.flushEffects()
385​
386 expect(query1.data()).toStrictEqual('Some data')
387 expect(query2.fetchStatus()).toStrictEqual('fetching')
388​
389 flush()
390​
391 expect(query2.fetchStatus()).toStrictEqual('idle')
392 expect(query2.status()).toStrictEqual('success')
393 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
394 expect(dependentQueryFn).toHaveBeenCalledWith(
395 expect.objectContaining({ queryKey: ['dependant2'] }),
396 )
397 }))
398​
399 test('should use the current value for the queryKey when refetch is called', fakeAsync(() => {
400 const fetchFn = vi.fn(simpleFetcher)
401 const keySignal = signal('key11')
402​
403 const query = TestBed.runInInjectionContext(() => {
404 return injectQuery(() => ({
405 queryKey: ['key10', keySignal()],
406 queryFn: fetchFn,
407 enabled: false,
408 }))
409 })
410​
411 expect(fetchFn).not.toHaveBeenCalled()
412​
413 query.refetch().then(() => {
414 expect(fetchFn).toHaveBeenCalledTimes(1)
415 expect(fetchFn).toHaveBeenCalledWith(
416 expect.objectContaining({
417 queryKey: ['key10', 'key11'],
418 }),
419 )
420 })
421​
422 flush()
423​
424 keySignal.set('key12')
425​
426 TestBed.flushEffects()
427​
428 query.refetch().then(() => {
429 expect(fetchFn).toHaveBeenCalledTimes(2)
430 expect(fetchFn).toHaveBeenCalledWith(
431 expect.objectContaining({
432 queryKey: ['key10', 'key12'],
433 }),
434 )
435 })
436​
437 flush()
438 }))
439​
440 describe('throwOnError', () => {
441 test('should evaluate throwOnError when query is expected to throw', fakeAsync(() => {
442 const boundaryFn = vi.fn()
443 TestBed.runInInjectionContext(() => {
444 return injectQuery(() => ({
445 queryKey: ['key12'],
446 queryFn: rejectFetcher,
447 throwOnError: boundaryFn,
448 }))
449 })
450​
451 flush()
452​
453 expect(boundaryFn).toHaveBeenCalledTimes(1)
454 expect(boundaryFn).toHaveBeenCalledWith(
455 Error('Some error'),
456 expect.objectContaining({
457 state: expect.objectContaining({ status: 'error' }),
458 }),
459 )
460 }))
461​
462 test('should throw when throwOnError is true', fakeAsync(() => {
463 TestBed.runInInjectionContext(() => {
464 return injectQuery(() => ({
465 queryKey: ['key13'],
466 queryFn: rejectFetcher,
467 throwOnError: true,
468 }))
469 })
470​
471 expect(() => {
472 flush()
473 }).toThrowError('Some error')
474 flush()
475 }))
476​
477 test('should throw when throwOnError function returns true', fakeAsync(() => {
478 TestBed.runInInjectionContext(() => {
479 return injectQuery(() => ({
480 queryKey: ['key14'],
481 queryFn: rejectFetcher,
482 throwOnError: () => true,
483 }))
484 })
485​
486 expect(() => {
487 flush()
488 }).toThrowError('Some error')
489 flush()
490 }))
491 })
492​
493 test('should set state to error when queryFn returns reject promise', fakeAsync(() => {
494 const query = TestBed.runInInjectionContext(() => {
495 return injectQuery(() => ({
496 retry: false,
497 queryKey: ['key15'],
498 queryFn: rejectFetcher,
499 }))
500 })
501​
502 expect(query.status()).toBe('pending')
503​
504 flush()
505​
506 expect(query.status()).toBe('error')
507 }))
508​
509 test('should render with required signal inputs', fakeAsync(async () => {
510 @Component({
511 selector: 'app-fake',
512 template: `{{ query.data() }}`,
513 standalone: true,
514 })
515 class FakeComponent {
516 name = input.required<string>()
517​
518 query = injectQuery(() => ({
519 queryKey: ['fake', this.name()],
520 queryFn: () => Promise.resolve(this.name()),
521 }))
522 }
523​
524 const fixture = TestBed.createComponent(FakeComponent)
525 setSignalInputs(fixture.componentInstance, {
526 name: 'signal-input-required-test',
527 })
528​
529 flush()
530 fixture.detectChanges()
531​
532 expect(fixture.debugElement.nativeElement.textContent).toEqual(
533 'signal-input-required-test',
534 )
535 }))
536​
537 test('should run optionsFn in injection context', fakeAsync(async () => {
538 @Injectable()
539 class FakeService {
540 getData(name: string) {
541 return Promise.resolve(name)
542 }
543 }
544​
545 @Component({
546 selector: 'app-fake',
547 template: `{{ query.data() }}`,
548 standalone: true,
549 providers: [FakeService],
550 })
551 class FakeComponent {
552 name = signal<string>('test name')
553​
554 query = injectQuery(() => {
555 const service = inject(FakeService)
556​
557 return {
558 queryKey: ['fake', this.name()],
559 queryFn: () => {
560 return service.getData(this.name())
561 },
562 }
563 })
564 }
565​
566 const fixture = TestBed.createComponent(FakeComponent)
567 fixture.detectChanges()
568 flush()
569​
570 expect(fixture.componentInstance.query.data()).toEqual('test name')
571​
572 fixture.componentInstance.name.set('test name 2')
573 fixture.detectChanges()
574 flush()
575​
576 expect(fixture.componentInstance.query.data()).toEqual('test name 2')
577 }))
578​
579 test('should run optionsFn in injection context and allow passing injector to queryFn', fakeAsync(async () => {
580 @Injectable()
581 class FakeService {
582 getData(name: string) {
583 return Promise.resolve(name)
584 }
585 }
586​
587 @Component({
588 selector: 'app-fake',
589 template: `{{ query.data() }}`,
590 standalone: true,
591 providers: [FakeService],
592 })
593 class FakeComponent {
594 name = signal<string>('test name')
595​
596 query = injectQuery(() => {
597 const injector = inject(Injector)
598​
599 return {
600 queryKey: ['fake', this.name()],
601 queryFn: () => {
602 const service = injector.get(FakeService)
603 return service.getData(this.name())
604 },
605 }
606 })
607 }
608​
609 const fixture = TestBed.createComponent(FakeComponent)
610 fixture.detectChanges()
611 flush()
612​
613 expect(fixture.componentInstance.query.data()).toEqual('test name')
614​
615 fixture.componentInstance.name.set('test name 2')
616 fixture.detectChanges()
617 flush()
618​
619 expect(fixture.componentInstance.query.data()).toEqual('test name 2')
620 }))
621​
622 describe('injection context', () => {
623 test('throws NG0203 with descriptive error outside injection context', () => {
624 expect(() => {
625 injectQuery(() => ({
626 queryKey: ['injectionContextError'],
627 queryFn: simpleFetcher,
628 }))
629 }).toThrowError(/NG0203(.*?)injectQuery/)
630 })
631​
632 test('can be used outside injection context when passing an injector', () => {
633 const query = injectQuery(
634 () => ({
635 queryKey: ['manualInjector'],
636 queryFn: simpleFetcher,
637 }),
638 TestBed.inject(Injector),
639 )
640​
641 expect(query.status()).toBe('pending')
642 })
643 })
644})