Open History to see the last commit
1import { assertType, describe, expectTypeOf, it } from 'vitest'
2import { computed, reactive, ref } from 'vue-demi'
3import { dataTagSymbol, skipToken } from '@tanstack/query-core'
4import { createKey } from '@tanstack/query-test-utils'
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})