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

useQuery.test-d.tsx

330 lines10.6 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 | undefined>()
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 | undefined>()
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 | undefined>()
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 | undefined>()
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' | undefined>()
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' | undefined>()
61 })
62​
63 it('should error when the query function result does not match with the specified type', () => {
64 assertType(
65 useQuery<number>(() => ({
66 queryKey: key,
67 // @ts-expect-error
68 queryFn: () => 'test',
69 })),
70 )
71 })
72​
73 it('should infer the result type from a generic query function', () => {
74 function queryFn<T = string>(): Promise<T> {
75 return Promise.resolve({} as T)
76 }
77​
78 const fromGenericQueryFn = useQuery(() => ({
79 queryKey: key,
80 queryFn: () => queryFn(),
81 }))
82 expectTypeOf(fromGenericQueryFn.data).toEqualTypeOf<string | undefined>()
83 expectTypeOf(fromGenericQueryFn.error).toEqualTypeOf<Error | null>()
84 })
85​
86 it("should accept a query function typed with 'QueryFunction'", () => {
87 type MyData = number
88 type MyQueryKey = readonly ['my-data', number]
89​
90 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
91 queryKey: [, n],
92 }) => {
93 return n + 42
94 }
95​
96 useQuery(() => ({
97 queryKey: ['my-data', 100] as const,
98 queryFn: getMyDataArrayKey,
99 }))
100​
101 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
102 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
103 return Number(context.queryKey[0]) + 42
104 }
105​
106 useQuery(() => ({
107 queryKey: ['1'] as ['1'],
108 queryFn: getMyDataStringKey,
109 }))
110 })
111​
112 it('should handle query functions that return Promise<any>', () => {
113 const result = useQuery(() => ({
114 queryKey: key,
115 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
116 }))
117 expectTypeOf(result.data).toEqualTypeOf<any>()
118 })
119​
120 it('should handle wrapped queries with custom fetcher passed as inline queryFn', () => {
121 const useWrappedQuery = <
122 TQueryKey extends [string, Record<string, unknown>?],
123 TQueryFnData,
124 TError,
125 TData = TQueryFnData,
126 >(
127 qk: TQueryKey,
128 fetcher: (
129 obj: TQueryKey[1],
130 token: string,
131 // return type must be wrapped with TQueryFnReturn
132 ) => Promise<TQueryFnData>,
133 options?: OmitKeyof<
134 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
135 'queryKey' | 'queryFn' | 'initialData',
136 'safely'
137 >,
138 ) =>
139 useQuery(() => ({
140 queryKey: qk,
141 queryFn: () => fetcher(qk[1], 'token'),
142 ...options,
143 }))
144 const test = useWrappedQuery([''], () => Promise.resolve('1'))
145 expectTypeOf(test.data).toEqualTypeOf<string | undefined>()
146 })
147​
148 it('should handle wrapped queries with custom fetcher passed directly to useQuery', () => {
149 const useWrappedFuncStyleQuery = <
150 TQueryKey extends [string, Record<string, unknown>?],
151 TQueryFnData,
152 TError,
153 TData = TQueryFnData,
154 >(
155 qk: TQueryKey,
156 fetcher: () => Promise<TQueryFnData>,
157 options?: OmitKeyof<
158 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
159 'queryKey' | 'queryFn' | 'initialData',
160 'safely'
161 >,
162 ) => useQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
163 const testFuncStyle = useWrappedFuncStyleQuery([''], () =>
164 Promise.resolve(true),
165 )
166 expectTypeOf(testFuncStyle.data).toEqualTypeOf<boolean | undefined>()
167 })
168​
169 it('should return the correct states for a successful query', () => {
170 const state = useQuery<string, Error>(() => ({
171 queryKey: key,
172 queryFn: () => Promise.resolve('test'),
173 }))
174​
175 if (state.isPending) {
176 expectTypeOf(state.data).toEqualTypeOf<undefined>()
177 expectTypeOf(state.error).toEqualTypeOf<null>()
178 } else if (state.isLoadingError) {
179 expectTypeOf(state.data).toEqualTypeOf<undefined>()
180 expectTypeOf(state.error).toEqualTypeOf<Error>()
181 } else {
182 expectTypeOf(state.data).toEqualTypeOf<string>()
183 expectTypeOf(state.error).toEqualTypeOf<Error | null>()
184 }
185 })
186​
187 describe('initialData', () => {
188 describe('Config object overload', () => {
189 it('should always define TData when initialData is provided as an object', () => {
190 const query = useQuery(() => ({
191 queryKey: createKey(),
192 queryFn: () => ({ wow: true }),
193 initialData: { wow: true },
194 }))
195​
196 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean }>()
197 })
198​
199 it('should define TData when passed through queryOptions', () => {
200 const options = queryOptions({
201 queryKey: createKey(),
202 queryFn: () => ({ wow: true }),
203 initialData: { wow: true },
204 })
205 const query = useQuery(() => options)
206​
207 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean }>()
208 })
209​
210 it('should always define TData when initialData is provided as a function which ALWAYS returns the data', () => {
211 const query = useQuery(() => ({
212 queryKey: createKey(),
213 queryFn: () => ({ wow: true }),
214 initialData: () => ({ wow: true }),
215 }))
216​
217 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean }>()
218 })
219​
220 it('should have undefined in the TData union when initialData is NOT provided', () => {
221 const query = useQuery(() => ({
222 queryKey: createKey(),
223 queryFn: () => ({ wow: true }),
224 }))
225​
226 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean } | undefined>()
227 })
228​
229 it('should have undefined in the TData union when initialData is provided as a function which can return undefined', () => {
230 const query = useQuery(() => ({
231 queryKey: createKey(),
232 queryFn: () => ({ wow: true }),
233 initialData: () => undefined as { wow: boolean } | undefined,
234 }))
235​
236 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean } | undefined>()
237 })
238 })
239​
240 describe('Query key overload', () => {
241 it('should always define TData when initialData is provided', () => {
242 const query = useQuery(() => ({
243 queryKey: createKey(),
244 queryFn: () => ({ wow: true }),
245 initialData: { wow: true },
246 }))
247​
248 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean }>()
249 })
250​
251 it('should have undefined in the TData union when initialData is NOT provided', () => {
252 const query = useQuery(() => ({
253 queryKey: createKey(),
254 queryFn: () => ({ wow: true }),
255 }))
256​
257 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean } | undefined>()
258 })
259 })
260​
261 describe('Query key and func', () => {
262 it('should always define TData when initialData is provided', () => {
263 const query = useQuery(() => ({
264 queryKey: createKey(),
265 queryFn: () => ({ wow: true }),
266 initialData: { wow: true },
267 }))
268​
269 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean }>()
270 })
271​
272 it('should have undefined in the TData union when initialData is NOT provided', () => {
273 const query = useQuery(() => ({
274 queryKey: createKey(),
275 queryFn: () => ({ wow: true }),
276 }))
277​
278 expectTypeOf(query.data).toEqualTypeOf<{ wow: boolean } | undefined>()
279 })
280 })
281 })
282​
283 describe('generic indexed access TData', () => {
284 // https://github.com/TanStack/query/issues/9937
285 it('should be assignable back to its source indexed type when passed to a generic function parameter', () => {
286 enum DataType {
287 Account = 'account',
288 Product = 'product',
289 }
290​
291 interface Account {
292 name: string
293 }
294 interface Product {
295 code: string
296 }
297​
298 type DataTypeToEntity = {
299 [DataType.Account]: Account
300 [DataType.Product]: Product
301 }
302​
303 const getData = <TDataType extends DataType>(
304 _dataType: TDataType,
305 ): Promise<DataTypeToEntity[TDataType]> =>
306 Promise.resolve({} as DataTypeToEntity[TDataType])
307​
308 const getLabel = <TDataType extends DataType>(
309 _dataType: TDataType,
310 _data: DataTypeToEntity[TDataType],
311 ) => 'test'
312​
313 function Test<TDataType extends DataType>(props: {
314 dataType: TDataType
315 }) {
316 const query = useQuery(() => ({
317 queryKey: ['test'],
318 queryFn: () => getData(props.dataType),
319 }))
320​
321 // Regression guard: this call must compile. With the previous
322 // hand-rolled NoInfer, `data` failed to flow back into the generic
323 // indexed-access parameter `DataTypeToEntity[TDataType]`.
324 return query.data ? getLabel(props.dataType, query.data) : null
325 }
326​
327 expectTypeOf(Test).toBeFunction()
328 })
329 })
330})