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

useQuery.test-d.tsx

315 lines10.1 KB

1import { assertType, describe, expectTypeOf, it } from 'vitest'
2import { createKey } from '@tanstack/query-test-utils'
3import { queryOptions, useQuery } from '../index'
4import type { OmitKeyof, QueryFunction, UseQueryOptions } from '..'
5​
6describe('useQuery', () => {
7 const key = createKey()
8​
9 it('should default to unknown when the query function is unspecified', () => {
10 const noQueryFn = useQuery(() => ({ queryKey: key }))
11 expectTypeOf(noQueryFn.data).toEqualTypeOf<unknown>()
12 expectTypeOf(noQueryFn.error).toEqualTypeOf<Error | null>()
13 })
14​
15 it('should infer the result type from the query function', () => {
16 const fromQueryFn = useQuery(() => ({
17 queryKey: key,
18 queryFn: () => 'test',
19 }))
20 expectTypeOf(fromQueryFn.data).toEqualTypeOf<string>()
21 expectTypeOf(fromQueryFn.error).toEqualTypeOf<Error | null>()
22 })
23​
24 it('should be possible to specify the result type', () => {
25 const withResult = useQuery<string>(() => ({
26 queryKey: key,
27 queryFn: () => 'test',
28 }))
29 expectTypeOf(withResult.data).toEqualTypeOf<string>()
30 expectTypeOf(withResult.error).toEqualTypeOf<Error | null>()
31 })
32​
33 it('should be possible to specify the error type', () => {
34 const withError = useQuery<string, Error>(() => ({
35 queryKey: key,
36 queryFn: () => 'test',
37 }))
38 expectTypeOf(withError.data).toEqualTypeOf<string>()
39 expectTypeOf(withError.error).toEqualTypeOf<Error | null>()
40 })
41​
42 it('should provide the result type in the configuration', () => {
43 const result = useQuery(() => ({
44 queryKey: [key],
45 queryFn: () => true,
46 }))
47 expectTypeOf(result.data).toEqualTypeOf<boolean>()
48 })
49​
50 it('should be possible to specify a union type as result type', () => {
51 const unionTypeSync = useQuery(() => ({
52 queryKey: key,
53 queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
54 }))
55 expectTypeOf(unionTypeSync.data).toEqualTypeOf<'a' | 'b'>()
56 const unionTypeAsync = useQuery<'a' | 'b'>(() => ({
57 queryKey: key,
58 queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
59 }))
60 expectTypeOf(unionTypeAsync.data).toEqualTypeOf<'a' | 'b'>()
61 })
62​
63 it('should error when the query function result does not match with the specified type', () => {
64 assertType(
65 // @ts-expect-error
66 useQuery<number>(() => ({ queryKey: key, queryFn: () => 'test' })),
67 )
68 })
69​
70 it('should infer the result type from a generic query function', () => {
71 function queryFn<T = string>(): Promise<T> {
72 return Promise.resolve({} as T)
73 }
74​
75 const fromGenericQueryFn = useQuery(() => ({
76 queryKey: key,
77 queryFn: () => queryFn(),
78 }))
79 expectTypeOf(fromGenericQueryFn.data).toEqualTypeOf<string>()
80 expectTypeOf(fromGenericQueryFn.error).toEqualTypeOf<Error | null>()
81​
82 const fromGenericOptionsQueryFn = useQuery(() => ({
83 queryKey: key,
84 queryFn: () => queryFn(),
85 }))
86 expectTypeOf(fromGenericOptionsQueryFn.data).toEqualTypeOf<string>()
87 expectTypeOf(fromGenericOptionsQueryFn.error).toEqualTypeOf<Error | null>()
88​
89 type MyData = number
90 type MyQueryKey = readonly ['my-data', number]
91​
92 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
93 queryKey: [, n],
94 }) => {
95 return n + 42
96 }
97​
98 useQuery(() => ({
99 queryKey: ['my-data', 100] as const,
100 queryFn: getMyDataArrayKey,
101 }))
102​
103 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
104 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
105 return Number(context.queryKey[0]) + 42
106 }
107​
108 useQuery(() => ({
109 queryKey: ['1'] as ['1'],
110 queryFn: getMyDataStringKey,
111 }))
112 })
113​
114 it('should handle query-functions that return Promise<any>', () => {
115 const result = useQuery(() => ({
116 queryKey: key,
117 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
118 }))
119 expectTypeOf(result.data).toBeAny()
120 })
121​
122 it('should handle wrapped queries with custom fetcher passed as inline queryFn', () => {
123 const useWrappedQuery = <
124 TQueryKey extends [string, Record<string, unknown>?],
125 TQueryFnData,
126 TError,
127 TData = TQueryFnData,
128 >(
129 qk: TQueryKey,
130 fetcher: (
131 obj: TQueryKey[1],
132 token: string,
133 // return type must be wrapped with TQueryFnReturn
134 ) => Promise<TQueryFnData>,
135 options?: OmitKeyof<
136 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
137 'queryKey' | 'queryFn' | 'initialData',
138 'safely'
139 >,
140 ) =>
141 useQuery(() => ({
142 queryKey: qk,
143 queryFn: () => fetcher(qk[1], 'token'),
144 ...options,
145 }))
146 const test = useWrappedQuery([''], () => Promise.resolve('1'))
147 expectTypeOf(test.data).toEqualTypeOf<string>()
148 })
149​
150 it('should handle wrapped queries with custom fetcher passed directly to useQuery', () => {
151 const useWrappedFuncStyleQuery = <
152 TQueryKey extends [string, Record<string, unknown>?],
153 TQueryFnData,
154 TError,
155 TData = TQueryFnData,
156 >(
157 qk: TQueryKey,
158 fetcher: () => Promise<TQueryFnData>,
159 options?: OmitKeyof<
160 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
161 'queryKey' | 'queryFn' | 'initialData',
162 'safely'
163 >,
164 ) => useQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
165 const testFuncStyle = useWrappedFuncStyleQuery([''], () =>
166 Promise.resolve(true),
167 )
168 expectTypeOf(testFuncStyle.data).toEqualTypeOf<boolean>()
169 })
170​
171 describe('initialData', () => {
172 describe('Config object overload', () => {
173 it('should always define TData when initialData is provided as an object', () => {
174 const query = useQuery(() => ({
175 queryKey: createKey(),
176 queryFn: () => ({ wow: true }),
177 initialData: { wow: true },
178 }))
179​
180 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean }>()
181 })
182​
183 it('should define TData when passed through queryOptions', () => {
184 const options = queryOptions({
185 queryKey: createKey(),
186 queryFn: () => ({ wow: true }),
187 initialData: { wow: true },
188 })
189 const query = useQuery(() => options)
190​
191 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean }>()
192 })
193​
194 it('should always define TData when initialData is provided as a function which ALWAYS returns the data', () => {
195 const query = useQuery(() => ({
196 queryKey: createKey(),
197 queryFn: () => ({ wow: true }),
198 initialData: () => ({ wow: true }),
199 }))
200​
201 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean }>()
202 })
203​
204 it('tData should be non-optional on the result even when initialData is NOT provided: data is a suspending read', () => {
205 const { data } = useQuery(() => ({
206 queryKey: createKey(),
207 queryFn: () => ({ wow: true }),
208 }))
209​
210 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
211 })
212​
213 it('should not have undefined in the TData union when initialData is provided as a function which can return undefined', () => {
214 const query = useQuery(() => ({
215 queryKey: createKey(),
216 queryFn: () => ({ wow: true }),
217 initialData: () => undefined as { wow: boolean } | undefined,
218 }))
219​
220 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean }>()
221 })
222 })
223​
224 describe('Query key overload', () => {
225 it('should always define TData when initialData is provided', () => {
226 const query = useQuery(() => ({
227 queryKey: createKey(),
228 queryFn: () => ({ wow: true }),
229 initialData: { wow: true },
230 }))
231​
232 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean }>()
233 })
234​
235 it('tData should be non-optional on the result even when initialData is NOT provided: data is a suspending read', () => {
236 const { data } = useQuery(() => ({
237 queryKey: createKey(),
238 queryFn: () => ({ wow: true }),
239 }))
240​
241 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
242 })
243 })
244​
245 describe('Query key and func', () => {
246 it('should always define TData when initialData is provided', () => {
247 const query = useQuery(() => ({
248 queryKey: createKey(),
249 queryFn: () => ({ wow: true }),
250 initialData: { wow: true },
251 }))
252​
253 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean }>()
254 })
255​
256 it('tData should be non-optional on the result even when initialData is NOT provided: data is a suspending read', () => {
257 const { data } = useQuery(() => ({
258 queryKey: createKey(),
259 queryFn: () => ({ wow: true }),
260 }))
261​
262 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
263 })
264 })
265 })
266​
267 describe('generic indexed access TData', () => {
268 // https://github.com/TanStack/query/issues/9937
269 it('should be assignable back to its source indexed type when passed to a generic function parameter', () => {
270 enum DataType {
271 Account = 'account',
272 Product = 'product',
273 }
274​
275 interface Account {
276 name: string
277 }
278 interface Product {
279 code: string
280 }
281​
282 type DataTypeToEntity = {
283 [DataType.Account]: Account
284 [DataType.Product]: Product
285 }
286​
287 const getData = <TDataType extends DataType>(
288 _dataType: TDataType,
289 ): Promise<DataTypeToEntity[TDataType]> =>
290 Promise.resolve({} as DataTypeToEntity[TDataType])
291​
292 const getLabel = <TDataType extends DataType>(
293 _dataType: TDataType,
294 _data: DataTypeToEntity[TDataType],
295 ) => 'test'
296​
297 function Test<TDataType extends DataType>(props: {
298 dataType: TDataType
299 }) {
300 const query = useQuery(() => ({
301 queryKey: ['test'],
302 queryFn: () => getData(props.dataType),
303 }))
304​
305 // Regression guard: this call must compile. With the previous
306 // hand-rolled NoInfer, `data` failed to flow back into the generic
307 // indexed-access parameter `DataTypeToEntity[TDataType]`.
308 // (`data` is now a non-optional suspending read, so no guard needed.)
309 return getLabel(props.dataType, query.data)
310 }
311​
312 expectTypeOf(Test).toBeFunction()
313 })
314 })
315})