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

queryOptions.test-d.ts

515 lines14.4 KB

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 properly type value when passed to setQueryData', () => {
193 const key = createKey()
194 const { queryKey: tagged } = queryOptions({
195 queryKey: key,
196 queryFn: () => Promise.resolve(5),
197 })
198​
199 const queryClient = new QueryClient()
200​
201 // @ts-expect-error value should be a number
202 queryClient.setQueryData(tagged, '5')
203 // @ts-expect-error value should be a number
204 queryClient.setQueryData(tagged, () => '5')
205​
206 const data = queryClient.setQueryData(tagged, 5)
207​
208 expectTypeOf(data).toEqualTypeOf<number | undefined>()
209 })
210​
211 it('should infer even if there is a conditional skipToken', () => {
212 const key = createKey()
213 const { queryKey: tagged } = queryOptions({
214 queryKey: key,
215 queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5),
216 })
217​
218 const queryClient = new QueryClient()
219 const data = queryClient.getQueryData(tagged)
220​
221 expectTypeOf(data).toEqualTypeOf<number | undefined>()
222 })
223​
224 it('should infer to unknown if we disable a query with just a skipToken', () => {
225 const key = createKey()
226 const { queryKey: tagged } = queryOptions({
227 queryKey: key,
228 queryFn: skipToken,
229 })
230​
231 const queryClient = new QueryClient()
232 const data = queryClient.getQueryData(tagged)
233​
234 expectTypeOf(data).toEqualTypeOf<unknown>()
235 expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<unknown>()
236 })
237​
238 it('should allow to be passed to QueryClient methods while containing getter', () => {
239 const ref1 = ref(1)
240 const ref2 = ref(2)
241 const options = queryOptions(() => ({
242 queryKey: [...createKey(), ref1.value, { nested: ref2.value }],
243 queryFn: () => Promise.resolve(5),
244 }))
245​
246 const queryClient = new QueryClient()
247​
248 // Should not error
249 const data = queryClient.invalidateQueries(options)
250 // Should not error
251 // oxlint-disable-next-line tanstack-query/no-restricted-syntax -- grandfathered direct test
252 const data2 = queryClient.fetchQuery(options)
253​
254 expectTypeOf(data).toEqualTypeOf<Promise<void>>()
255 expectTypeOf(data2).toEqualTypeOf<Promise<number>>()
256 })
257​
258 it('should always define TData when initialData is provided as a function which ALWAYS returns the data', () => {
259 const key = createKey()
260 const { data } = reactive(
261 useQuery(
262 queryOptions({
263 queryKey: key,
264 queryFn: () => {
265 return {
266 wow: true,
267 }
268 },
269 initialData: () => ({
270 wow: true,
271 }),
272 }),
273 ),
274 )
275​
276 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
277 })
278​
279 it('should have undefined in the TData union when initialData is NOT provided', () => {
280 const key = createKey()
281 const { data } = reactive(
282 useQuery(
283 queryOptions({
284 queryKey: key,
285 queryFn: () => {
286 return {
287 wow: true,
288 }
289 },
290 }),
291 ),
292 )
293​
294 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
295 })
296​
297 it('should have undefined in the TData union when initialData is provided as a function which can return undefined', () => {
298 const key = createKey()
299 const { data } = reactive(
300 useQuery(
301 queryOptions({
302 queryKey: key,
303 queryFn: () => {
304 return {
305 wow: true,
306 }
307 },
308 initialData: () => undefined as { wow: boolean } | undefined,
309 }),
310 ),
311 )
312​
313 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
314 })
315​
316 it('should narrow TData after an isSuccess check when initialData is provided as a function which can return undefined', () => {
317 const key = createKey()
318 const { data, isSuccess } = reactive(
319 useQuery(
320 queryOptions({
321 queryKey: key,
322 queryFn: () => {
323 return {
324 wow: true,
325 }
326 },
327 initialData: () => undefined as { wow: boolean } | undefined,
328 }),
329 ),
330 )
331​
332 if (isSuccess) {
333 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
334 }
335 })
336​
337 it('should not have undefined in data when initialData is provided', () => {
338 const key = createKey()
339 const { data } = reactive(
340 useQuery(
341 queryOptions({
342 queryKey: key,
343 initialData: 42,
344 }),
345 ),
346 )
347​
348 expectTypeOf(data).toEqualTypeOf<number>()
349 })
350​
351 it('should allow optional initialData object', () => {
352 const options = queryOptions({
353 queryKey: createKey(),
354 queryFn: () => Promise.resolve('something string'),
355 initialData: Math.random() > 0.5 ? 'initial string' : undefined,
356 })
357​
358 expectTypeOf(options.initialData).toExtend<
359 InitialDataFunction<string> | string | undefined
360 >()
361 })
362​
363 it('should allow undefined response in initialData', () => {
364 assertType((id: string | null) =>
365 queryOptions({
366 queryKey: [...createKey(), id],
367 queryFn: () =>
368 Promise.resolve({
369 id: '1',
370 title: 'Do Laundry',
371 }),
372 initialData: () =>
373 !id
374 ? undefined
375 : {
376 id,
377 title: 'Initial Data',
378 },
379 }),
380 )
381 })
382​
383 it('should allow accessing queryFn and other properties on the returned options object', () => {
384 const options = queryOptions({
385 queryKey: createKey(),
386 queryFn: () => Promise.resolve([]),
387 })
388​
389 expectTypeOf(options.queryFn).not.toBeUndefined()
390 expectTypeOf(options.queryKey).not.toBeUndefined()
391 expectTypeOf(options.staleTime).not.toBeUndefined()
392 })
393​
394 it('should allow accessing queryFn and other properties on the returned options when used with getter', () => {
395 const options = queryOptions(() => ({
396 queryKey: createKey(),
397 queryFn: () => Promise.resolve([]),
398 }))
399​
400 const resolvedGetter = options()
401​
402 expectTypeOf(resolvedGetter.queryFn).not.toBeUndefined()
403 expectTypeOf(resolvedGetter.queryKey).not.toBeUndefined()
404 })
405​
406 it('should allow computed ref as enabled property', () => {
407 const enabled = computed(() => true)
408​
409 // This was broken in #10452, fixed in #10458
410 const options = queryOptions({
411 queryKey: createKey(),
412 queryFn: () => Promise.resolve(1),
413 enabled,
414 })
415​
416 expectTypeOf(options.queryKey).not.toBeUndefined()
417 })
418​
419 it('should allow ref as enabled property', () => {
420 const enabled = ref(true)
421​
422 const options = queryOptions({
423 queryKey: createKey(),
424 queryFn: () => Promise.resolve(1),
425 enabled,
426 })
427​
428 expectTypeOf(options.queryKey).not.toBeUndefined()
429 })
430​
431 it('should allow boolean as enabled property', () => {
432 const options = queryOptions({
433 queryKey: createKey(),
434 queryFn: () => Promise.resolve(1),
435 enabled: true,
436 })
437​
438 expectTypeOf(options.queryKey).not.toBeUndefined()
439 })
440​
441 it('should allow getter function as enabled property', () => {
442 const options = queryOptions({
443 queryKey: createKey(),
444 queryFn: () => Promise.resolve(1),
445 enabled: () => true,
446 })
447​
448 expectTypeOf(options.queryKey).not.toBeUndefined()
449 })
450​
451 it('should allow computed ref as queryKey', () => {
452 const id = ref<string | null>('1')
453​
454 // This was broken in #10452, the #10465 fix only covered `enabled`
455 const options = queryOptions({
456 queryKey: computed(() => ['foo', id.value] as const),
457 queryFn: () => Promise.resolve({ id: '1' }),
458 })
459​
460 expectTypeOf(options.queryKey).not.toBeUndefined()
461 })
462​
463 it('should allow ref as queryKey', () => {
464 const keyRef = ref(['foo', '1'] as const)
465​
466 const options = queryOptions({
467 queryKey: keyRef,
468 queryFn: () => Promise.resolve({ id: '1' }),
469 })
470​
471 expectTypeOf(options.queryKey).not.toBeUndefined()
472 })
473​
474 it('should allow getter function as queryKey', () => {
475 const id = ref<string | null>('1')
476​
477 const options = queryOptions({
478 queryKey: () => ['foo', id.value] as const,
479 queryFn: () => Promise.resolve({ id: '1' }),
480 })
481​
482 expectTypeOf(options.queryKey).not.toBeUndefined()
483 })
484​
485 it('should allow computed queryFn resolving to skipToken', () => {
486 const id = ref<string | null>('1')
487​
488 const options = queryOptions({
489 queryKey: computed(() => ['foo', id.value]),
490 queryFn: computed(() =>
491 id.value ? () => Promise.resolve({ id: '1' }) : skipToken,
492 ),
493 })
494​
495 const { data } = reactive(useQuery(options))
496​
497 expectTypeOf(data).toEqualTypeOf<{ id: string } | undefined>()
498 })
499​
500 it('should allow skipToken inside a whole-options getter', () => {
501 const id = ref<string | null>('1')
502​
503 const options = queryOptions(() => {
504 const current = id.value
505 return {
506 queryKey: ['foo', current],
507 queryFn: current ? () => Promise.resolve({ id: current }) : skipToken,
508 }
509 })
510​
511 const { data } = reactive(useQuery(options))
512​
513 expectTypeOf(data).toEqualTypeOf<{ id: string } | undefined>()
514 })
515})