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

queryOptions.test-d.ts

568 lines15.9 KB

1import { dataTagSymbol, skipToken } from '@tanstack/query-core'
2import { createKey } from '@tanstack/query-test-utils'
3import { assertType, describe, expectTypeOf, it } from 'vitest'
4import { computed, reactive, ref } from 'vue-demi'
5import { QueryClient } from '../queryClient'
6import { queryOptions } from '../queryOptions'
7import { useQueries } from '../useQueries'
8import { useQuery } from '../useQuery'
9import type { InitialDataFunction } from '@tanstack/query-core'
10​
11// Regression test for exported queryOptions inference under declaration emit.
12// TypeScript should be able to name the return type without expanding the
13// internal data tag symbols into the consumer's .d.ts output.
14export const exportedQueryOptions = queryOptions({
15 queryKey: ['invalid'],
16})
17​
18export const exportedQueryOptionsGetter = queryOptions(() => ({
19 queryKey: ['invalid'],
20}))
21​
22describe('queryOptions', () => {
23 it('should not allow excess properties', () => {
24 const key = createKey()
25 assertType(
26 queryOptions({
27 // @ts-expect-error this is a good error, because stallTime does not exist!
28 queryKey: key,
29 queryFn: () => Promise.resolve(5),
30 stallTime: 1000,
31 }),
32 )
33 })
34​
35 it('should infer types for callbacks', () => {
36 const key = createKey()
37 queryOptions({
38 queryKey: key,
39 queryFn: () => Promise.resolve(5),
40 staleTime: 1000,
41 select: (data) => {
42 expectTypeOf(data).toEqualTypeOf<number>()
43 },
44 })
45 })
46​
47 it('should work when passed to useQuery', () => {
48 const key = createKey()
49 const options = queryOptions({
50 queryKey: key,
51 queryFn: () => Promise.resolve(5),
52 })
53​
54 const { data } = reactive(useQuery(options))
55 expectTypeOf(data).toEqualTypeOf<number | undefined>()
56 })
57​
58 it('should work when passed to useQueries', () => {
59 const options = queryOptions({
60 queryKey: createKey(),
61 queryFn: () => Promise.resolve(5),
62 })
63​
64 const { value: queriesState } = useQueries({ queries: [options] })
65​
66 expectTypeOf(queriesState[0].data).toEqualTypeOf<number | undefined>()
67 })
68​
69 it('should work when passed to query', async () => {
70 const options = queryOptions({
71 queryKey: ['key'],
72 queryFn: () => Promise.resolve(5),
73 })
74​
75 const data = await new QueryClient().query(options)
76 expectTypeOf(data).toEqualTypeOf<number>()
77 })
78​
79 it('should work when passed to query with select', async () => {
80 const options = queryOptions({
81 queryKey: ['key'],
82 queryFn: () => Promise.resolve(5),
83 select: (data) => data.toString(),
84 })
85​
86 const data = await new QueryClient().query(options)
87 expectTypeOf(data).toEqualTypeOf<string>()
88 })
89​
90 it('should work when passed to query with enabled: false', async () => {
91 const options = queryOptions({
92 queryKey: ['key'],
93 queryFn: () => Promise.resolve(5),
94 enabled: false,
95 })
96​
97 const data = await new QueryClient().query(options)
98 expectTypeOf(data).toEqualTypeOf<number>()
99 })
100​
101 it('should work when passed to query with skipToken', async () => {
102 const options = queryOptions({
103 queryKey: ['key'],
104 queryFn: skipToken,
105 })
106​
107 const data = await new QueryClient().query(options)
108 expectTypeOf(data).toEqualTypeOf<unknown>()
109 })
110​
111 it('should tag the queryKey with the result type of the QueryFn', () => {
112 const key = createKey()
113 const { queryKey: tagged } = queryOptions({
114 queryKey: key,
115 queryFn: () => Promise.resolve(5),
116 })
117​
118 expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<number>()
119 })
120​
121 it('should tag the queryKey even if no promise is returned', () => {
122 const key = createKey()
123 const { queryKey: tagged } = queryOptions({
124 queryKey: key,
125 queryFn: () => 5,
126 })
127​
128 expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<number>()
129 })
130​
131 it('should tag the queryKey with unknown if there is no queryFn', () => {
132 const key = createKey()
133 const { queryKey: tagged } = queryOptions({
134 queryKey: key,
135 })
136​
137 expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<unknown>()
138 })
139​
140 it('should tag the queryKey with the result type of the QueryFn if select is used', () => {
141 const key = createKey()
142 const { queryKey: tagged } = queryOptions({
143 queryKey: key,
144 queryFn: () => Promise.resolve(5),
145 select: (data) => data.toString(),
146 })
147​
148 expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<number>()
149 })
150​
151 it('should return the proper type when passed to getQueryData', () => {
152 const key = createKey()
153 const { queryKey: tagged } = queryOptions({
154 queryKey: key,
155 queryFn: () => Promise.resolve(5),
156 })
157​
158 const queryClient = new QueryClient()
159 const data = queryClient.getQueryData(tagged)
160​
161 expectTypeOf(data).toEqualTypeOf<number | undefined>()
162 })
163​
164 it('should return the proper type when passed to getQueryState', () => {
165 const key = createKey()
166 const { queryKey: tagged } = queryOptions({
167 queryKey: key,
168 queryFn: () => Promise.resolve(5),
169 })
170​
171 const queryClient = new QueryClient()
172 const state = queryClient.getQueryState(tagged)
173​
174 expectTypeOf(state?.data).toEqualTypeOf<number | undefined>()
175 })
176​
177 it('should properly type updaterFn when passed to setQueryData', () => {
178 const key = createKey()
179 const { queryKey: tagged } = queryOptions({
180 queryKey: key,
181 queryFn: () => Promise.resolve(5),
182 })
183​
184 const queryClient = new QueryClient()
185 const data = queryClient.setQueryData(tagged, (prev) => {
186 expectTypeOf(prev).toEqualTypeOf<number | undefined>()
187 return prev
188 })
189 expectTypeOf(data).toEqualTypeOf<number | undefined>()
190 })
191​
192 it('should preserve discriminated union narrowing in setQueryData updaterFn', () => {
193 type Data =
194 | { kind: 'a'; value: number; requiredA: number }
195 | { kind: 'b'; value: number; requiredB: number }
196​
197 const key = createKey()
198 const { queryKey: tagged } = queryOptions({
199 queryKey: key,
200 queryFn: (): Promise<Data> =>
201 Promise.resolve({
202 kind: 'a',
203 value: 1,
204 requiredA: 1,
205 }),
206 })
207​
208 const queryClient = new QueryClient()
209 queryClient.setQueryData(tagged, (prev) => {
210 if (!prev || prev.kind !== 'a') {
211 return prev
212 }
213​
214 expectTypeOf(prev).toEqualTypeOf<Extract<Data, { kind: 'a' }>>()
215 return { ...prev, value: prev.value + 1 }
216 })
217​
218 // @ts-expect-error updater input should be inferred from the tagged query key
219 queryClient.setQueryData(tagged, (prev: string | undefined) => prev)
220 })
221​
222 it('should properly type value when passed to setQueryData', () => {
223 const key = createKey()
224 const { queryKey: tagged } = queryOptions({
225 queryKey: key,
226 queryFn: () => Promise.resolve(5),
227 })
228​
229 const queryClient = new QueryClient()
230​
231 // @ts-expect-error value should be a number
232 queryClient.setQueryData(tagged, '5')
233 // @ts-expect-error value should be a number
234 queryClient.setQueryData(tagged, () => '5')
235​
236 const data = queryClient.setQueryData(tagged, 5)
237​
238 expectTypeOf(data).toEqualTypeOf<number | undefined>()
239 })
240​
241 it('should infer even if there is a conditional skipToken', () => {
242 const key = createKey()
243 const { queryKey: tagged } = queryOptions({
244 queryKey: key,
245 queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5),
246 })
247​
248 const queryClient = new QueryClient()
249 const data = queryClient.getQueryData(tagged)
250​
251 expectTypeOf(data).toEqualTypeOf<number | undefined>()
252 })
253​
254 it('should infer to unknown if we disable a query with just a skipToken', () => {
255 const key = createKey()
256 const { queryKey: tagged } = queryOptions({
257 queryKey: key,
258 queryFn: skipToken,
259 })
260​
261 const queryClient = new QueryClient()
262 const data = queryClient.getQueryData(tagged)
263​
264 expectTypeOf(data).toEqualTypeOf<unknown>()
265 expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<unknown>()
266 })
267​
268 it('should allow to be passed to QueryClient methods while containing getter', () => {
269 const ref1 = ref(1)
270 const ref2 = ref(2)
271 const options = queryOptions(() => ({
272 queryKey: [...createKey(), ref1.value, { nested: ref2.value }],
273 queryFn: () => Promise.resolve(5),
274 }))
275​
276 const queryClient = new QueryClient()
277​
278 // Should not error
279 const data = queryClient.invalidateQueries(options)
280 // Should not error
281 // oxlint-disable-next-line tanstack-query/no-restricted-syntax -- grandfathered direct test
282 const data2 = queryClient.fetchQuery(options)
283​
284 expectTypeOf(data).toEqualTypeOf<Promise<void>>()
285 expectTypeOf(data2).toEqualTypeOf<Promise<number>>()
286 })
287​
288 it('should always define TData when initialData is provided as a function which ALWAYS returns the data', () => {
289 const key = createKey()
290 const { data } = reactive(
291 useQuery(
292 queryOptions({
293 queryKey: key,
294 queryFn: () => {
295 return {
296 wow: true,
297 }
298 },
299 initialData: () => ({
300 wow: true,
301 }),
302 }),
303 ),
304 )
305​
306 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
307 })
308​
309 it('should have undefined in the TData union when initialData is NOT provided', () => {
310 const key = createKey()
311 const { data } = reactive(
312 useQuery(
313 queryOptions({
314 queryKey: key,
315 queryFn: () => {
316 return {
317 wow: true,
318 }
319 },
320 }),
321 ),
322 )
323​
324 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
325 })
326​
327 it('should have undefined in the TData union when initialData is provided as a function which can return undefined', () => {
328 const key = createKey()
329 const { data } = reactive(
330 useQuery(
331 queryOptions({
332 queryKey: key,
333 queryFn: () => {
334 return {
335 wow: true,
336 }
337 },
338 initialData: () => undefined as { wow: boolean } | undefined,
339 }),
340 ),
341 )
342​
343 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
344 })
345​
346 it('should narrow TData after an isSuccess check when initialData is provided as a function which can return undefined', () => {
347 const key = createKey()
348 const { data, isSuccess } = reactive(
349 useQuery(
350 queryOptions({
351 queryKey: key,
352 queryFn: () => {
353 return {
354 wow: true,
355 }
356 },
357 initialData: () => undefined as { wow: boolean } | undefined,
358 }),
359 ),
360 )
361​
362 if (isSuccess) {
363 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
364 }
365 })
366​
367 it('should not have undefined in data when initialData is provided', () => {
368 const key = createKey()
369 const { data } = reactive(
370 useQuery(
371 queryOptions({
372 queryKey: key,
373 initialData: 42,
374 }),
375 ),
376 )
377​
378 expectTypeOf(data).toEqualTypeOf<number>()
379 })
380​
381 it('should allow optional initialData object', () => {
382 const options = queryOptions({
383 queryKey: createKey(),
384 queryFn: () => Promise.resolve('something string'),
385 initialData: Math.random() > 0.5 ? 'initial string' : undefined,
386 })
387​
388 expectTypeOf(options.initialData).toExtend<
389 InitialDataFunction<string> | string | undefined
390 >()
391 })
392​
393 it('should allow undefined response in initialData', () => {
394 assertType((id: string | null) =>
395 queryOptions({
396 queryKey: [...createKey(), id],
397 queryFn: () =>
398 Promise.resolve({
399 id: '1',
400 title: 'Do Laundry',
401 }),
402 initialData: () =>
403 !id
404 ? undefined
405 : {
406 id,
407 title: 'Initial Data',
408 },
409 }),
410 )
411 })
412​
413 it('should allow accessing queryFn and other properties on the returned options object', () => {
414 const options = queryOptions({
415 queryKey: createKey(),
416 queryFn: () => Promise.resolve([]),
417 })
418​
419 expectTypeOf(options.queryFn).not.toBeUndefined()
420 expectTypeOf(options.queryKey).not.toBeUndefined()
421 expectTypeOf(options.staleTime).not.toBeUndefined()
422 })
423​
424 it('should allow accessing queryFn and other properties on the returned options when used with getter', () => {
425 const options = queryOptions(() => ({
426 queryKey: createKey(),
427 queryFn: () => Promise.resolve([]),
428 }))
429​
430 const resolvedGetter = options()
431​
432 expectTypeOf(resolvedGetter.queryFn).not.toBeUndefined()
433 expectTypeOf(resolvedGetter.queryKey).not.toBeUndefined()
434 })
435​
436 it('should allow computed ref as enabled property', () => {
437 const enabled = computed(() => true)
438​
439 // This was broken in #10452, fixed in #10458
440 const options = queryOptions({
441 queryKey: createKey(),
442 queryFn: () => Promise.resolve(1),
443 enabled,
444 })
445​
446 expectTypeOf(options.queryKey).not.toBeUndefined()
447 })
448​
449 it('should allow ref as enabled property', () => {
450 const enabled = ref(true)
451​
452 const options = queryOptions({
453 queryKey: createKey(),
454 queryFn: () => Promise.resolve(1),
455 enabled,
456 })
457​
458 expectTypeOf(options.queryKey).not.toBeUndefined()
459 })
460​
461 it('should allow boolean as enabled property', () => {
462 const options = queryOptions({
463 queryKey: createKey(),
464 queryFn: () => Promise.resolve(1),
465 enabled: true,
466 })
467​
468 expectTypeOf(options.queryKey).not.toBeUndefined()
469 })
470​
471 it('should allow getter function as enabled property', () => {
472 const options = queryOptions({
473 queryKey: createKey(),
474 queryFn: () => Promise.resolve(1),
475 enabled: () => true,
476 })
477​
478 expectTypeOf(options.queryKey).not.toBeUndefined()
479 })
480​
481 it('should allow a getter that returns boolean or undefined', () => {
482 const someRef = ref<boolean | undefined>(false)
483​
484 const options = queryOptions({
485 queryKey: createKey(),
486 queryFn: () => Promise.resolve(1),
487 enabled: () => someRef.value,
488 })
489​
490 expectTypeOf(options.queryKey).not.toBeUndefined()
491 })
492​
493 it('should type enabled with the query argument from query-core', () => {
494 queryOptions({
495 queryKey: ['post'] as const,
496 queryFn: () => Promise.resolve(1),
497 enabled: (query) => {
498 expectTypeOf(query.queryKey).toEqualTypeOf<readonly ['post']>()
499 return query.state.status !== 'pending'
500 },
501 })
502 })
503​
504 it('should allow computed ref as queryKey', () => {
505 const id = ref<string | null>('1')
506​
507 // This was broken in #10452, the #10465 fix only covered `enabled`
508 const options = queryOptions({
509 queryKey: computed(() => ['foo', id.value] as const),
510 queryFn: () => Promise.resolve({ id: '1' }),
511 })
512​
513 expectTypeOf(options.queryKey).not.toBeUndefined()
514 })
515​
516 it('should allow ref as queryKey', () => {
517 const keyRef = ref(['foo', '1'] as const)
518​
519 const options = queryOptions({
520 queryKey: keyRef,
521 queryFn: () => Promise.resolve({ id: '1' }),
522 })
523​
524 expectTypeOf(options.queryKey).not.toBeUndefined()
525 })
526​
527 it('should allow getter function as queryKey', () => {
528 const id = ref<string | null>('1')
529​
530 const options = queryOptions({
531 queryKey: () => ['foo', id.value] as const,
532 queryFn: () => Promise.resolve({ id: '1' }),
533 })
534​
535 expectTypeOf(options.queryKey).not.toBeUndefined()
536 })
537​
538 it('should allow computed queryFn resolving to skipToken', () => {
539 const id = ref<string | null>('1')
540​
541 const options = queryOptions({
542 queryKey: computed(() => ['foo', id.value]),
543 queryFn: computed(() =>
544 id.value ? () => Promise.resolve({ id: '1' }) : skipToken,
545 ),
546 })
547​
548 const { data } = reactive(useQuery(options))
549​
550 expectTypeOf(data).toEqualTypeOf<{ id: string } | undefined>()
551 })
552​
553 it('should allow skipToken inside a whole-options getter', () => {
554 const id = ref<string | null>('1')
555​
556 const options = queryOptions(() => {
557 const current = id.value
558 return {
559 queryKey: ['foo', current],
560 queryFn: current ? () => Promise.resolve({ id: current }) : skipToken,
561 }
562 })
563​
564 const { data } = reactive(useQuery(options))
565​
566 expectTypeOf(data).toEqualTypeOf<{ id: string } | undefined>()
567 })
568})