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