Open History to see the last commit
1import { queryKey } from '@tanstack/query-test-utils'
2import { describe, expectTypeOf, it } from 'vitest'
3β
4import { queryOptions } from '../queryOptions'
5import { useQuery } from '../useQuery'
6import type { OmitKeyof, QueryFunction, UseQueryOptions } from '..'
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).not.toHaveProperty('promise')
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 type MyData = number
73 type MyQueryKey = readonly ['my-data', number]
74β
75 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
76 queryKey: [, n],
77 }) => {
78 return Promise.resolve(n + 42)
79 }
80β
81 useQuery({
82 queryKey: ['my-data', 100],
83 queryFn: getMyDataArrayKey,
84 })
85β
86 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
87 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
88 return Promise.resolve(Number(context.queryKey[0]) + 42)
89 }
90β
91 useQuery({
92 queryKey: ['1'],
93 queryFn: getMyDataStringKey,
94 })
95β
96 // it should handle query-functions that return Promise<any>
97 useQuery({
98 queryKey: key,
99 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
100 })
101β
102 // handles wrapped queries with custom fetcher passed as inline queryFn
103 const useWrappedQuery = <
104 TQueryKey extends [string, Record<string, unknown>?],
105 TQueryFnData,
106 TError,
107 TData = TQueryFnData,
108 >(
109 qk: TQueryKey,
110 fetcher: (
111 obj: TQueryKey[1],
112 token: string,
113 // return type must be wrapped with TQueryFnReturn
114 ) => Promise<TQueryFnData>,
115 options?: OmitKeyof<
116 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
117 'queryKey' | 'queryFn' | 'initialData'
118 >,
119 ) =>
120 useQuery({
121 queryKey: qk,
122 queryFn: () => fetcher(qk[1], 'token'),
123 ...options,
124 })
125 const testQuery = useWrappedQuery([''], () => Promise.resolve('1'))
126 expectTypeOf(testQuery.data).toEqualTypeOf<string | undefined>()
127β
128 // handles wrapped queries with custom fetcher passed directly to useQuery
129 const useWrappedFuncStyleQuery = <
130 TQueryKey extends [string, Record<string, unknown>?],
131 TQueryFnData,
132 TError,
133 TData = TQueryFnData,
134 >(
135 qk: TQueryKey,
136 fetcher: () => Promise<TQueryFnData>,
137 options?: OmitKeyof<
138 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
139 'queryKey' | 'queryFn' | 'initialData'
140 >,
141 ) => useQuery({ queryKey: qk, queryFn: fetcher, ...options })
142 const testFuncStyle = useWrappedFuncStyleQuery([''], () =>
143 Promise.resolve(true),
144 )
145 expectTypeOf(testFuncStyle.data).toEqualTypeOf<boolean | undefined>()
146β
147 it('should return the correct states for a successful query', () => {
148 const state = useQuery<string, Error>({
149 queryKey: key,
150 queryFn: () => Promise.resolve('test'),
151 })
152β
153 if (state.isPending) {
154 expectTypeOf(state.data).toEqualTypeOf<undefined>()
155 expectTypeOf(state.error).toEqualTypeOf<null>()
156 return <span>pending</span>
157 }
158β
159 if (state.isLoadingError) {
160 expectTypeOf(state.data).toEqualTypeOf<undefined>()
161 expectTypeOf(state.error).toEqualTypeOf<Error>()
162 return <span>{state.error.message}</span>
163 }
164β
165 expectTypeOf(state.data).toEqualTypeOf<string>()
166 expectTypeOf(state.error).toEqualTypeOf<Error | null>()
167 return <span>{state.data}</span>
168 })
169β
170 describe('initialData', () => {
171 describe('Config object overload', () => {
172 it('should always define TData when initialData is provided as an object', () => {
173 const { data } = useQuery({
174 queryKey: queryKey(),
175 queryFn: () => ({ wow: true }),
176 initialData: { wow: true },
177 })
178β
179 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
180 })
181β
182 it('should define TData when passed through queryOptions', () => {
183 const options = queryOptions({
184 queryKey: queryKey(),
185 queryFn: () => {
186 return {
187 wow: true,
188 }
189 },
190 initialData: {
191 wow: true,
192 },
193 })
194 const { data } = useQuery(options)
195β
196 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
197 })
198β
199 it('should be possible to define a different TData than TQueryFnData using select with queryOptions spread into useQuery', () => {
200 const options = queryOptions({
201 queryKey: queryKey(),
202 queryFn: () => Promise.resolve(1),
203 })
204β
205 const query = useQuery({
206 ...options,
207 select: (data) => data > 1,
208 })
209β
210 expectTypeOf(query.data).toEqualTypeOf<boolean | undefined>()
211 })
212β
213 it('should always define TData when initialData is provided as a function which ALWAYS returns the data', () => {
214 const { data } = useQuery({
215 queryKey: queryKey(),
216 queryFn: () => {
217 return {
218 wow: true,
219 }
220 },
221 initialData: () => ({
222 wow: true,
223 }),
224 })
225β
226 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
227 })
228β
229 it('should have undefined in the TData union when initialData is NOT provided', () => {
230 const { data } = useQuery({
231 queryKey: queryKey(),
232 queryFn: () => {
233 return {
234 wow: true,
235 }
236 },
237 })
238β
239 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
240 })
241β
242 it('should have undefined in the TData union when initialData is provided as a function which can return undefined', () => {
243 const { data } = useQuery({
244 queryKey: queryKey(),
245 queryFn: () => {
246 return {
247 wow: true,
248 }
249 },
250 initialData: () => undefined as { wow: boolean } | undefined,
251 })
252β
253 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
254 })
255β
256 it('should narrow TData after an isSuccess check when initialData is provided as a function which can return undefined', () => {
257 const { data, isSuccess } = useQuery({
258 queryKey: queryKey(),
259 queryFn: () => {
260 return {
261 wow: true,
262 }
263 },
264 initialData: () => undefined as { wow: boolean } | undefined,
265 })
266β
267 if (isSuccess) {
268 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
269 }
270 })
271β
272 it('should not have undefined in data when initialData is provided', () => {
273 const { data } = useQuery({
274 queryKey: queryKey(),
275 initialData: 42,
276 })
277β
278 expectTypeOf(data).toEqualTypeOf<number>()
279 })
280 })
281β
282 it('should preserve discriminated-union narrowing', () => {
283 type Result =
284 | { type: 'first'; first: string }
285 | { type: 'second'; second: string }
286β
287 const query = useQuery({
288 queryKey: queryKey(),
289 queryFn: (): Result => ({ type: 'first', first: 'a' }),
290 })
291β
292 const second = query.data?.type === 'first' ? undefined : query.data
293β
294 expectTypeOf(second).toEqualTypeOf<
295 { type: 'second'; second: string } | undefined
296 >()
297 })
298β
299 describe('custom hook', () => {
300 it('should allow custom hooks using UseQueryOptions', () => {
301 type Data = string
302β
303 const useCustomQuery = (
304 options?: OmitKeyof<UseQueryOptions<Data>, 'queryKey' | 'queryFn'>,
305 ) => {
306 return useQuery({
307 ...options,
308 queryKey: queryKey(),
309 queryFn: () => Promise.resolve('data'),
310 })
311 }
312β
313 const { data } = useCustomQuery()
314β
315 expectTypeOf(data).toEqualTypeOf<Data | undefined>()
316 })
317 })
318β
319 describe('structuralSharing', () => {
320 it('should be able to use structuralSharing with unknown types', () => {
321 // https://github.com/TanStack/query/issues/6525#issuecomment-1938411343
322 useQuery({
323 queryKey: queryKey(),
324 queryFn: () => 5,
325 structuralSharing: (oldData, newData) => {
326 expectTypeOf(oldData).toBeUnknown()
327 expectTypeOf(newData).toBeUnknown()
328 return newData
329 },
330 })
331 })
332 })
333 })
334})