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

useQuery.test-d.tsx

341 lines10.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: ['key'],
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: ['key'],
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: ['key'],
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: ['key'],
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: ['key'],
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: ['key'],
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: ['key'],
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: ['key'],
285 queryFn: () => {
286 return {
287 wow: true,
288 }
289 },
290 initialData: () => undefined as { wow: boolean } | undefined,
291 })
292​
293 void result
294 })
295​
296 it('data should not have undefined when initialData is provided', () => {
297 const { data } = useQuery({
298 queryKey: ['query-key'],
299 initialData: 42,
300 })
301​
302 expectTypeOf(data).toEqualTypeOf<number>()
303 })
304 })
305​
306 describe('custom hook', () => {
307 it('should allow custom hooks using UseQueryOptions', () => {
308 type Data = string
309​
310 const useCustomQuery = (
311 options?: OmitKeyof<UseQueryOptions<Data>, 'queryKey' | 'queryFn'>,
312 ) => {
313 return useQuery({
314 ...options,
315 queryKey: ['todos-key'],
316 queryFn: () => Promise.resolve('data'),
317 })
318 }
319​
320 const { data } = useCustomQuery()
321​
322 expectTypeOf(data).toEqualTypeOf<Data | undefined>()
323 })
324 })
325​
326 describe('structuralSharing', () => {
327 it('should be able to use structuralSharing with unknown types', () => {
328 // https://github.com/TanStack/query/issues/6525#issuecomment-1938411343
329 useQuery({
330 queryKey: ['key'],
331 queryFn: () => 5,
332 structuralSharing: (oldData, newData) => {
333 expectTypeOf(oldData).toBeUnknown()
334 expectTypeOf(newData).toBeUnknown()
335 return newData
336 },
337 })
338 })
339 })
340 })
341})