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

useQuery.test-d.tsx

408 lines12.4 KB

1import { describe, expectTypeOf, it } from 'vitest'
2import { queryKey } from '@tanstack/query-test-utils'
3import { useQuery } from '../useQuery'
4import { queryOptions } from '../queryOptions'
5import type { OmitKeyof, QueryFunction, UseQueryOptions } from '..'
6​
7describe('useQuery', () => {
8 const key = queryKey()
9​
10 // unspecified query function should default to unknown
11 const noQueryFn = useQuery({ queryKey: key })
12 expectTypeOf(noQueryFn.data).toEqualTypeOf<unknown>()
13 expectTypeOf(noQueryFn.error).toEqualTypeOf<Error | null>()
14​
15 // it should infer the result type from the query function
16 const fromQueryFn = useQuery({ queryKey: key, queryFn: () => 'test' })
17 expectTypeOf(fromQueryFn.data).toEqualTypeOf<string | undefined>()
18 expectTypeOf(fromQueryFn.error).toEqualTypeOf<Error | null>()
19 expectTypeOf(fromQueryFn.promise).toEqualTypeOf<Promise<string>>()
20​
21 // it should be possible to specify the result type
22 const withResult = useQuery<string>({
23 queryKey: key,
24 queryFn: () => 'test',
25 })
26 expectTypeOf(withResult.data).toEqualTypeOf<string | undefined>()
27 expectTypeOf(withResult.error).toEqualTypeOf<Error | null>()
28​
29 // it should be possible to specify the error type
30 const withError = useQuery<string, Error>({
31 queryKey: key,
32 queryFn: () => 'test',
33 })
34 expectTypeOf(withError.data).toEqualTypeOf<string | undefined>()
35 expectTypeOf(withError.error).toEqualTypeOf<Error | null>()
36​
37 // it should provide the result type in the configuration
38 useQuery({
39 queryKey: [key],
40 queryFn: () => Promise.resolve(true),
41 })
42​
43 // it should be possible to specify a union type as result type
44 const unionTypeSync = useQuery({
45 queryKey: key,
46 queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
47 })
48 expectTypeOf(unionTypeSync.data).toEqualTypeOf<'a' | 'b' | undefined>()
49 const unionTypeAsync = useQuery<'a' | 'b'>({
50 queryKey: key,
51 queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
52 })
53 expectTypeOf(unionTypeAsync.data).toEqualTypeOf<'a' | 'b' | undefined>()
54​
55 // should error when the query function result does not match with the specified type
56 // @ts-expect-error
57 useQuery<number>({ queryKey: key, queryFn: () => 'test' })
58​
59 // it should infer the result type from a generic query function
60 function queryFn<T = string>(): Promise<T> {
61 return Promise.resolve({} as T)
62 }
63​
64 const fromGenericQueryFn = useQuery({
65 queryKey: key,
66 queryFn: () => queryFn(),
67 })
68 expectTypeOf(fromGenericQueryFn.data).toEqualTypeOf<string | undefined>()
69 expectTypeOf(fromGenericQueryFn.error).toEqualTypeOf<Error | null>()
70​
71 const fromGenericOptionsQueryFn = useQuery({
72 queryKey: key,
73 queryFn: () => queryFn(),
74 })
75 expectTypeOf(fromGenericOptionsQueryFn.data).toEqualTypeOf<
76 string | undefined
77 >()
78 expectTypeOf(fromGenericOptionsQueryFn.error).toEqualTypeOf<Error | null>()
79​
80 type MyData = number
81 type MyQueryKey = readonly ['my-data', number]
82​
83 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
84 queryKey: [, n],
85 }) => {
86 return Promise.resolve(n + 42)
87 }
88​
89 useQuery({
90 queryKey: ['my-data', 100],
91 queryFn: getMyDataArrayKey,
92 })
93​
94 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
95 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
96 return Promise.resolve(Number(context.queryKey[0]) + 42)
97 }
98​
99 useQuery({
100 queryKey: ['1'],
101 queryFn: getMyDataStringKey,
102 })
103​
104 // it should handle query-functions that return Promise<any>
105 useQuery({
106 queryKey: key,
107 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
108 })
109​
110 // handles wrapped queries with custom fetcher passed as inline queryFn
111 const useWrappedQuery = <
112 TQueryKey extends [string, Record<string, unknown>?],
113 TQueryFnData,
114 TError,
115 TData = TQueryFnData,
116 >(
117 qk: TQueryKey,
118 fetcher: (
119 obj: TQueryKey[1],
120 token: string,
121 // return type must be wrapped with TQueryFnReturn
122 ) => Promise<TQueryFnData>,
123 options?: OmitKeyof<
124 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
125 'queryKey' | 'queryFn' | 'initialData'
126 >,
127 ) =>
128 useQuery({
129 queryKey: qk,
130 queryFn: () => fetcher(qk[1], 'token'),
131 ...options,
132 })
133 const testQuery = useWrappedQuery([''], () => Promise.resolve('1'))
134 expectTypeOf(testQuery.data).toEqualTypeOf<string | undefined>()
135​
136 // handles wrapped queries with custom fetcher passed directly to useQuery
137 const useWrappedFuncStyleQuery = <
138 TQueryKey extends [string, Record<string, unknown>?],
139 TQueryFnData,
140 TError,
141 TData = TQueryFnData,
142 >(
143 qk: TQueryKey,
144 fetcher: () => Promise<TQueryFnData>,
145 options?: OmitKeyof<
146 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
147 'queryKey' | 'queryFn' | 'initialData'
148 >,
149 ) => useQuery({ queryKey: qk, queryFn: fetcher, ...options })
150 const testFuncStyle = useWrappedFuncStyleQuery([''], () =>
151 Promise.resolve(true),
152 )
153 expectTypeOf(testFuncStyle.data).toEqualTypeOf<boolean | undefined>()
154​
155 it('should return the correct states for a successful query', () => {
156 const state = useQuery<string, Error>({
157 queryKey: key,
158 queryFn: () => Promise.resolve('test'),
159 })
160​
161 if (state.isPending) {
162 expectTypeOf(state.data).toEqualTypeOf<undefined>()
163 expectTypeOf(state.error).toEqualTypeOf<null>()
164 return <span>pending</span>
165 }
166​
167 if (state.isLoadingError) {
168 expectTypeOf(state.data).toEqualTypeOf<undefined>()
169 expectTypeOf(state.error).toEqualTypeOf<Error>()
170 return <span>{state.error.message}</span>
171 }
172​
173 expectTypeOf(state.data).toEqualTypeOf<string>()
174 expectTypeOf(state.error).toEqualTypeOf<Error | null>()
175 return <span>{state.data}</span>
176 })
177​
178 describe('initialData', () => {
179 describe('Config object overload', () => {
180 it('TData should always be defined when initialData is provided as an object', () => {
181 const { data } = useQuery({
182 queryKey: queryKey(),
183 queryFn: () => ({ wow: true }),
184 initialData: { wow: true },
185 })
186​
187 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
188 })
189​
190 it('TData should be defined when passed through queryOptions', () => {
191 const options = queryOptions({
192 queryKey: queryKey(),
193 queryFn: () => {
194 return {
195 wow: true,
196 }
197 },
198 initialData: {
199 wow: true,
200 },
201 })
202 const { data } = useQuery(options)
203​
204 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
205 })
206​
207 it('should be possible to define a different TData than TQueryFnData using select with queryOptions spread into useQuery', () => {
208 const options = queryOptions({
209 queryKey: queryKey(),
210 queryFn: () => Promise.resolve(1),
211 })
212​
213 const query = useQuery({
214 ...options,
215 select: (data) => data > 1,
216 })
217​
218 expectTypeOf(query.data).toEqualTypeOf<boolean | undefined>()
219 })
220​
221 it('TData should always be defined when initialData is provided as a function which ALWAYS returns the data', () => {
222 const { data } = useQuery({
223 queryKey: queryKey(),
224 queryFn: () => {
225 return {
226 wow: true,
227 }
228 },
229 initialData: () => ({
230 wow: true,
231 }),
232 })
233​
234 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
235 })
236​
237 it('TData should have undefined in the union when initialData is NOT provided', () => {
238 const { data } = useQuery({
239 queryKey: queryKey(),
240 queryFn: () => {
241 return {
242 wow: true,
243 }
244 },
245 })
246​
247 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
248 })
249​
250 it('TData should have undefined in the union when initialData is provided as a function which can return undefined', () => {
251 const { data } = useQuery({
252 queryKey: queryKey(),
253 queryFn: () => {
254 return {
255 wow: true,
256 }
257 },
258 initialData: () => undefined as { wow: boolean } | undefined,
259 })
260​
261 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
262 })
263​
264 it('TData should be narrowed after an isSuccess check when initialData is provided as a function which can return undefined', () => {
265 const { data, isSuccess } = useQuery({
266 queryKey: queryKey(),
267 queryFn: () => {
268 return {
269 wow: true,
270 }
271 },
272 initialData: () => undefined as { wow: boolean } | undefined,
273 })
274​
275 if (isSuccess) {
276 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
277 }
278 })
279​
280 // eslint-disable-next-line vitest/expect-expect
281 it('TData should depend from only arguments, not the result', () => {
282 // @ts-expect-error
283 const result: UseQueryResult<{ wow: string }> = useQuery({
284 queryKey: queryKey(),
285 queryFn: () => {
286 return {
287 wow: true,
288 }
289 },
290 initialData: () => undefined as { wow: boolean } | undefined,
291 })
292​
293 void result
294 })
295​
296 // eslint-disable-next-line vitest/expect-expect
297 it('should preserve discriminated-union narrowing while keeping the reverse-inference guard', () => {
298 type Result =
299 | { type: 'first'; first: string }
300 | { type: 'second'; second: string }
301​
302 const query = useQuery({
303 queryKey: queryKey(),
304 queryFn: (): Result => ({ type: 'first', first: 'a' }),
305 })
306​
307 const second = query.data?.type === 'first' ? undefined : query.data
308​
309 expectTypeOf(second).toEqualTypeOf<
310 | { type: 'second'; second: string }
311 | undefined
312 >()
313 })
314​
315 it('data should not have undefined when initialData is provided', () => {
316 const { data } = useQuery({
317 queryKey: queryKey(),
318 initialData: 42,
319 })
320​
321 expectTypeOf(data).toEqualTypeOf<number>()
322 })
323 })
324​
325 describe('custom hook', () => {
326 it('should allow custom hooks using UseQueryOptions', () => {
327 type Data = string
328​
329 const useCustomQuery = (
330 options?: OmitKeyof<UseQueryOptions<Data>, 'queryKey' | 'queryFn'>,
331 ) => {
332 return useQuery({
333 ...options,
334 queryKey: queryKey(),
335 queryFn: () => Promise.resolve('data'),
336 })
337 }
338​
339 const { data } = useCustomQuery()
340​
341 expectTypeOf(data).toEqualTypeOf<Data | undefined>()
342 })
343 })
344​
345 describe('structuralSharing', () => {
346 it('should be able to use structuralSharing with unknown types', () => {
347 // https://github.com/TanStack/query/issues/6525#issuecomment-1938411343
348 useQuery({
349 queryKey: queryKey(),
350 queryFn: () => 5,
351 structuralSharing: (oldData, newData) => {
352 expectTypeOf(oldData).toBeUnknown()
353 expectTypeOf(newData).toBeUnknown()
354 return newData
355 },
356 })
357 })
358 })
359 })
360​
361 describe('generic indexed access TData', () => {
362 // https://github.com/TanStack/query/issues/9937
363 it('should be assignable back to its source indexed type when passed to a generic function parameter', () => {
364 enum DataType {
365 Account = 'account',
366 Product = 'product',
367 }
368​
369 interface Account {
370 name: string
371 }
372 interface Product {
373 code: string
374 }
375​
376 type DataTypeToEntity = {
377 [DataType.Account]: Account
378 [DataType.Product]: Product
379 }
380​
381 const getData = <TDataType extends DataType>(
382 _dataType: TDataType,
383 ): Promise<DataTypeToEntity[TDataType]> =>
384 Promise.resolve({} as DataTypeToEntity[TDataType])
385​
386 const getLabel = <TDataType extends DataType>(
387 _dataType: TDataType,
388 _data: DataTypeToEntity[TDataType],
389 ) => 'test'
390​
391 function Test<TDataType extends DataType>(props: {
392 dataType: TDataType
393 }) {
394 const { data } = useQuery({
395 queryKey: ['test'],
396 queryFn: () => getData(props.dataType),
397 })
398​
399 // Regression guard: this call must compile. With the previous
400 // hand-rolled NoInfer, `data` failed to flow back into the generic
401 // indexed-access parameter `DataTypeToEntity[TDataType]`.
402 return data ? getLabel(props.dataType, data) : null
403 }
404​
405 expectTypeOf(Test).toBeFunction()
406 })
407 })
408})