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

inject-query.test.ts

571 lines16.7 KB

1import {
2 Component,
3 Injector,
4 computed,
5 effect,
6 input,
7 provideZonelessChangeDetection,
8 signal,
9} from '@angular/core'
10import { TestBed } from '@angular/core/testing'
11import {
12 afterEach,
13 beforeEach,
14 describe,
15 expect,
16 expectTypeOf,
17 test,
18 vi,
19} from 'vitest'
20import { queryKey, sleep } from '@tanstack/query-test-utils'
21import { QueryCache, QueryClient, injectQuery, provideTanStackQuery } from '..'
22import { setSignalInputs } 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 provideZonelessChangeDetection(),
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([''], () => Promise.resolve('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([''], () => Promise.resolve(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: () => sleep(0).then(() => 'Some data'),
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: () => sleep(0).then(() => '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: () =>
303 sleep(0).then(() => Promise.reject(new Error('Some error'))),
304 }))
305 })
306​
307 await resolveQueries()
308​
309 expect(query.status()).toBe('error')
310 expect(query.data()).toBe(undefined)
311 expect(query.error()).toMatchObject({ message: 'Some error' })
312 expect(query.isPending()).toBe(false)
313 expect(query.isFetching()).toBe(false)
314 expect(query.isError()).toBe(true)
315 expect(query.failureCount()).toBe(1)
316 expect(query.failureReason()).toMatchObject({ message: 'Some error' })
317 })
318​
319 test('should update query on options contained signal change', async () => {
320 const key = signal(['key6', 'key7'])
321 const spy = vi.fn(() => sleep(0).then(() => 'Some data'))
322​
323 const query = TestBed.runInInjectionContext(() => {
324 return injectQuery(() => ({
325 queryKey: key(),
326 queryFn: spy,
327 }))
328 })
329​
330 await resolveQueries()
331​
332 expect(spy).toHaveBeenCalledTimes(1)
333​
334 expect(query.status()).toBe('success')
335​
336 key.set(['key8'])
337 TestBed.tick()
338​
339 expect(spy).toHaveBeenCalledTimes(2)
340 // should call queryFn with context containing the new queryKey
341 expect(spy).toBeCalledWith({
342 client: queryClient,
343 meta: undefined,
344 queryKey: ['key8'],
345 signal: expect.anything(),
346 })
347 })
348​
349 test('should only run query once enabled signal is set to true', async () => {
350 const spy = vi.fn(() => sleep(0).then(() => 'Some data'))
351 const enabled = signal(false)
352​
353 const query = TestBed.runInInjectionContext(() => {
354 return injectQuery(() => ({
355 queryKey: ['key9'],
356 queryFn: spy,
357 enabled: enabled(),
358 }))
359 })
360​
361 expect(spy).not.toHaveBeenCalled()
362 expect(query.status()).toBe('pending')
363​
364 enabled.set(true)
365 await resolveQueries()
366 expect(spy).toHaveBeenCalledTimes(1)
367 expect(query.status()).toBe('success')
368 })
369​
370 test('should properly execute dependant queries', async () => {
371 const query1 = TestBed.runInInjectionContext(() => {
372 return injectQuery(() => ({
373 queryKey: ['dependant1'],
374 queryFn: () => sleep(0).then(() => 'Some data'),
375 }))
376 })
377​
378 const dependentQueryFn = vi
379 .fn()
380 .mockImplementation(() => sleep(1000).then(() => 'Some data'))
381​
382 const query2 = TestBed.runInInjectionContext(() => {
383 return injectQuery(
384 computed(() => ({
385 queryKey: ['dependant2'],
386 queryFn: dependentQueryFn,
387 enabled: !!query1.data(),
388 })),
389 )
390 })
391​
392 expect(query1.data()).toStrictEqual(undefined)
393 expect(query2.fetchStatus()).toStrictEqual('idle')
394 expect(dependentQueryFn).not.toHaveBeenCalled()
395​
396 await resolveQueries()
397​
398 expect(query1.data()).toStrictEqual('Some data')
399 expect(query2.fetchStatus()).toStrictEqual('fetching')
400​
401 await vi.runAllTimersAsync()
402​
403 expect(query2.fetchStatus()).toStrictEqual('idle')
404 expect(query2.status()).toStrictEqual('success')
405 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
406 expect(dependentQueryFn).toHaveBeenCalledWith(
407 expect.objectContaining({ queryKey: ['dependant2'] }),
408 )
409 })
410​
411 test('should use the current value for the queryKey when refetch is called', async () => {
412 const fetchFn = vi.fn(() => sleep(0).then(() => 'Some data'))
413 const keySignal = signal('key11')
414​
415 const query = TestBed.runInInjectionContext(() => {
416 return injectQuery(() => ({
417 queryKey: ['key10', keySignal()],
418 queryFn: fetchFn,
419 enabled: false,
420 }))
421 })
422​
423 expect(fetchFn).not.toHaveBeenCalled()
424​
425 query.refetch().then(() => {
426 expect(fetchFn).toHaveBeenCalledTimes(1)
427 expect(fetchFn).toHaveBeenCalledWith(
428 expect.objectContaining({
429 queryKey: ['key10', 'key11'],
430 }),
431 )
432 })
433​
434 await resolveQueries()
435​
436 keySignal.set('key12')
437​
438 TestBed.tick()
439​
440 query.refetch().then(() => {
441 expect(fetchFn).toHaveBeenCalledTimes(2)
442 expect(fetchFn).toHaveBeenCalledWith(
443 expect.objectContaining({
444 queryKey: ['key10', 'key12'],
445 }),
446 )
447 })
448​
449 await resolveQueries()
450 })
451​
452 describe('throwOnError', () => {
453 test('should evaluate throwOnError when query is expected to throw', async () => {
454 const boundaryFn = vi.fn()
455 TestBed.runInInjectionContext(() => {
456 return injectQuery(() => ({
457 queryKey: ['key12'],
458 queryFn: () =>
459 sleep(0).then(() => Promise.reject(new Error('Some error'))),
460 throwOnError: boundaryFn,
461 }))
462 })
463​
464 await vi.runAllTimersAsync()
465​
466 expect(boundaryFn).toHaveBeenCalledTimes(1)
467 expect(boundaryFn).toHaveBeenCalledWith(
468 Error('Some error'),
469 expect.objectContaining({
470 state: expect.objectContaining({ status: 'error' }),
471 }),
472 )
473 })
474​
475 test('should throw when throwOnError is true', async () => {
476 TestBed.runInInjectionContext(() => {
477 return injectQuery(() => ({
478 queryKey: ['key13'],
479 queryFn: () =>
480 sleep(0).then(() => Promise.reject(new Error('Some error'))),
481 throwOnError: true,
482 }))
483 })
484​
485 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
486 })
487​
488 test('should throw when throwOnError function returns true', async () => {
489 TestBed.runInInjectionContext(() => {
490 return injectQuery(() => ({
491 queryKey: ['key14'],
492 queryFn: () =>
493 sleep(0).then(() => Promise.reject(new Error('Some error'))),
494 throwOnError: () => true,
495 }))
496 })
497​
498 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
499 })
500 })
501​
502 test('should set state to error when queryFn returns reject promise', async () => {
503 const query = TestBed.runInInjectionContext(() => {
504 return injectQuery(() => ({
505 retry: false,
506 queryKey: ['key15'],
507 queryFn: () =>
508 sleep(0).then(() => Promise.reject(new Error('Some error'))),
509 }))
510 })
511​
512 expect(query.status()).toBe('pending')
513​
514 await resolveQueries()
515​
516 expect(query.status()).toBe('error')
517 })
518​
519 test('should render with required signal inputs', async () => {
520 @Component({
521 selector: 'app-fake',
522 template: `{{ query.data() }}`,
523 standalone: true,
524 })
525 class FakeComponent {
526 name = input.required<string>()
527​
528 query = injectQuery(() => ({
529 queryKey: ['fake', this.name()],
530 queryFn: () => this.name(),
531 }))
532 }
533​
534 const fixture = TestBed.createComponent(FakeComponent)
535 setSignalInputs(fixture.componentInstance, {
536 name: 'signal-input-required-test',
537 })
538​
539 fixture.detectChanges()
540 await resolveQueries()
541​
542 expect(fixture.componentInstance.query.data()).toEqual(
543 'signal-input-required-test',
544 )
545 })
546​
547 describe('injection context', () => {
548 test('throws NG0203 with descriptive error outside injection context', () => {
549 expect(() => {
550 injectQuery(() => ({
551 queryKey: ['injectionContextError'],
552 queryFn: () => sleep(0).then(() => 'Some data'),
553 }))
554 }).toThrowError(/NG0203(.*?)injectQuery/)
555 })
556​
557 test('can be used outside injection context when passing an injector', () => {
558 const query = injectQuery(
559 () => ({
560 queryKey: ['manualInjector'],
561 queryFn: () => sleep(0).then(() => 'Some data'),
562 }),
563 {
564 injector: TestBed.inject(Injector),
565 },
566 )
567​
568 expect(query.status()).toBe('pending')
569 })
570 })
571})