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

useQuery.test-d.tsx

401 lines12.3 KB

1import { createKey } from '@tanstack/query-test-utils'
2import { assertType, describe, expectTypeOf, it } from 'vitest'
3import { queryOptions } from '../queryOptions'
4import { useQuery } from '../useQuery'
5import type { OmitKeyof, QueryFunction, UseQueryOptions } from '..'
6​
7describe('useQuery', () => {
8 const key = createKey()
9​
10 it('should default to unknown when the query function is unspecified', () => {
11 const noQueryFn = useQuery({ queryKey: key })
12 expectTypeOf(noQueryFn.data).toEqualTypeOf<unknown>()
13 expectTypeOf(noQueryFn.error).toEqualTypeOf<Error | null>()
14 })
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​
23 it('should be possible to specify the result type', () => {
24 const withResult = useQuery<string>({
25 queryKey: key,
26 queryFn: () => 'test',
27 })
28 expectTypeOf(withResult.data).toEqualTypeOf<string | undefined>()
29 expectTypeOf(withResult.error).toEqualTypeOf<Error | null>()
30 })
31​
32 it('should be possible to specify the error type', () => {
33 const withError = useQuery<string, Error>({
34 queryKey: key,
35 queryFn: () => 'test',
36 })
37 expectTypeOf(withError.data).toEqualTypeOf<string | undefined>()
38 expectTypeOf(withError.error).toEqualTypeOf<Error | null>()
39 })
40​
41 it('should provide the result type in the configuration', () => {
42 const result = useQuery({
43 queryKey: [key],
44 queryFn: () => Promise.resolve(true),
45 })
46 expectTypeOf(result.data).toEqualTypeOf<boolean | undefined>()
47 })
48​
49 it('should be possible to specify a union type as result type', () => {
50 const unionTypeSync = useQuery({
51 queryKey: key,
52 queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
53 })
54 expectTypeOf(unionTypeSync.data).toEqualTypeOf<'a' | 'b' | undefined>()
55 const unionTypeAsync = useQuery<'a' | 'b'>({
56 queryKey: key,
57 queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
58 })
59 expectTypeOf(unionTypeAsync.data).toEqualTypeOf<'a' | 'b' | undefined>()
60 })
61​
62 it('should error when the query function result does not match with the specified type', () => {
63 assertType(
64 useQuery<number>({
65 queryKey: key,
66 // @ts-expect-error
67 queryFn: () => 'test',
68 }),
69 )
70 })
71​
72 it('should infer the result type from a generic query function', () => {
73 function queryFn<T = string>(): Promise<T> {
74 return Promise.resolve({} as T)
75 }
76​
77 const fromGenericQueryFn = useQuery({
78 queryKey: key,
79 queryFn: () => queryFn(),
80 })
81 expectTypeOf(fromGenericQueryFn.data).toEqualTypeOf<string | undefined>()
82 expectTypeOf(fromGenericQueryFn.error).toEqualTypeOf<Error | null>()
83 })
84​
85 it("should accept a query function typed with 'QueryFunction'", () => {
86 type MyData = number
87 type MyQueryKey = readonly ['my-data', number]
88​
89 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
90 queryKey: [, n],
91 }) => {
92 return Promise.resolve(n + 42)
93 }
94​
95 useQuery({
96 queryKey: ['my-data', 100],
97 queryFn: getMyDataArrayKey,
98 })
99​
100 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
101 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
102 return Promise.resolve(Number(context.queryKey[0]) + 42)
103 }
104​
105 useQuery({
106 queryKey: ['1'],
107 queryFn: getMyDataStringKey,
108 })
109 })
110​
111 it('should handle query functions that return Promise<any>', () => {
112 const result = useQuery({
113 queryKey: key,
114 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
115 })
116 expectTypeOf(result.data).toEqualTypeOf<any>()
117 })
118​
119 it('should handle wrapped queries with custom fetcher passed as inline queryFn', () => {
120 const useWrappedQuery = <
121 TQueryKey extends [string, Record<string, unknown>?],
122 TQueryFnData,
123 TError,
124 TData = TQueryFnData,
125 >(
126 qk: TQueryKey,
127 fetcher: (
128 obj: TQueryKey[1],
129 token: string,
130 // return type must be wrapped with TQueryFnReturn
131 ) => Promise<TQueryFnData>,
132 options?: OmitKeyof<
133 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
134 'queryKey' | 'queryFn' | 'initialData'
135 >,
136 ) =>
137 useQuery({
138 queryKey: qk,
139 queryFn: () => fetcher(qk[1], 'token'),
140 ...options,
141 })
142 const testQuery = useWrappedQuery([''], () => Promise.resolve('1'))
143 expectTypeOf(testQuery.data).toEqualTypeOf<string | undefined>()
144 })
145​
146 it('should handle wrapped queries with custom fetcher passed directly to useQuery', () => {
147 const useWrappedFuncStyleQuery = <
148 TQueryKey extends [string, Record<string, unknown>?],
149 TQueryFnData,
150 TError,
151 TData = TQueryFnData,
152 >(
153 qk: TQueryKey,
154 fetcher: () => Promise<TQueryFnData>,
155 options?: OmitKeyof<
156 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
157 'queryKey' | 'queryFn' | 'initialData'
158 >,
159 ) => useQuery({ queryKey: qk, queryFn: fetcher, ...options })
160 const testFuncStyle = useWrappedFuncStyleQuery([''], () =>
161 Promise.resolve(true),
162 )
163 expectTypeOf(testFuncStyle.data).toEqualTypeOf<boolean | undefined>()
164 })
165​
166 it('should return the correct states for a successful query', () => {
167 const state = useQuery<string, Error>({
168 queryKey: key,
169 queryFn: () => Promise.resolve('test'),
170 })
171​
172 if (state.isPending) {
173 expectTypeOf(state.data).toEqualTypeOf<undefined>()
174 expectTypeOf(state.error).toEqualTypeOf<null>()
175 return <span>pending</span>
176 }
177​
178 if (state.isLoadingError) {
179 expectTypeOf(state.data).toEqualTypeOf<undefined>()
180 expectTypeOf(state.error).toEqualTypeOf<Error>()
181 return <span>{state.error.message}</span>
182 }
183​
184 expectTypeOf(state.data).toEqualTypeOf<string>()
185 expectTypeOf(state.error).toEqualTypeOf<Error | null>()
186 return <span>{state.data}</span>
187 })
188​
189 describe('initialData', () => {
190 describe('Config object overload', () => {
191 it('should always define TData when initialData is provided as an object', () => {
192 const { data } = useQuery({
193 queryKey: createKey(),
194 queryFn: () => ({ wow: true }),
195 initialData: { wow: true },
196 })
197​
198 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
199 })
200​
201 it('should define TData when passed through queryOptions', () => {
202 const options = queryOptions({
203 queryKey: createKey(),
204 queryFn: () => {
205 return {
206 wow: true,
207 }
208 },
209 initialData: {
210 wow: true,
211 },
212 })
213 const { data } = useQuery(options)
214​
215 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
216 })
217​
218 it('should be possible to define a different TData than TQueryFnData using select with queryOptions spread into useQuery', () => {
219 const options = queryOptions({
220 queryKey: createKey(),
221 queryFn: () => Promise.resolve(1),
222 })
223​
224 const query = useQuery({
225 ...options,
226 select: (data) => data > 1,
227 })
228​
229 expectTypeOf(query.data).toEqualTypeOf<boolean | undefined>()
230 })
231​
232 it('should always define TData when initialData is provided as a function which ALWAYS returns the data', () => {
233 const { data } = useQuery({
234 queryKey: createKey(),
235 queryFn: () => {
236 return {
237 wow: true,
238 }
239 },
240 initialData: () => ({
241 wow: true,
242 }),
243 })
244​
245 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
246 })
247​
248 it('should have undefined in the TData union when initialData is NOT provided', () => {
249 const { data } = useQuery({
250 queryKey: createKey(),
251 queryFn: () => {
252 return {
253 wow: true,
254 }
255 },
256 })
257​
258 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
259 })
260​
261 it('should have undefined in the TData union when initialData is provided as a function which can return undefined', () => {
262 const { data } = useQuery({
263 queryKey: createKey(),
264 queryFn: () => {
265 return {
266 wow: true,
267 }
268 },
269 initialData: () => undefined as { wow: boolean } | undefined,
270 })
271​
272 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
273 })
274​
275 it('should narrow TData after an isSuccess check when initialData is provided as a function which can return undefined', () => {
276 const { data, isSuccess } = useQuery({
277 queryKey: createKey(),
278 queryFn: () => {
279 return {
280 wow: true,
281 }
282 },
283 initialData: () => undefined as { wow: boolean } | undefined,
284 })
285​
286 if (isSuccess) {
287 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
288 }
289 })
290​
291 it('should preserve discriminated-union narrowing', () => {
292 type Result =
293 | { type: 'first'; first: string }
294 | { type: 'second'; second: string }
295​
296 const query = useQuery({
297 queryKey: createKey(),
298 queryFn: (): Result => ({ type: 'first', first: 'a' }),
299 })
300​
301 const second = query.data?.type === 'first' ? undefined : query.data
302​
303 expectTypeOf(second).toEqualTypeOf<
304 { type: 'second'; second: string } | undefined
305 >()
306 })
307​
308 it('should not have undefined in data when initialData is provided', () => {
309 const { data } = useQuery({
310 queryKey: createKey(),
311 initialData: 42,
312 })
313​
314 expectTypeOf(data).toEqualTypeOf<number>()
315 })
316 })
317​
318 describe('custom hook', () => {
319 it('should allow custom hooks using UseQueryOptions', () => {
320 type Data = string
321​
322 const useCustomQuery = (
323 options?: OmitKeyof<UseQueryOptions<Data>, 'queryKey' | 'queryFn'>,
324 ) => {
325 return useQuery({
326 ...options,
327 queryKey: createKey(),
328 queryFn: () => Promise.resolve('data'),
329 })
330 }
331​
332 const { data } = useCustomQuery()
333​
334 expectTypeOf(data).toEqualTypeOf<Data | undefined>()
335 })
336 })
337​
338 describe('structuralSharing', () => {
339 it('should be able to use structuralSharing with unknown types', () => {
340 // https://github.com/TanStack/query/issues/6525#issuecomment-1938411343
341 useQuery({
342 queryKey: createKey(),
343 queryFn: () => 5,
344 structuralSharing: (oldData, newData) => {
345 expectTypeOf(oldData).toBeUnknown()
346 expectTypeOf(newData).toBeUnknown()
347 return newData
348 },
349 })
350 })
351 })
352 })
353​
354 describe('generic indexed access TData', () => {
355 // https://github.com/TanStack/query/issues/9937
356 it('should be assignable back to its source indexed type when passed to a generic function parameter', () => {
357 enum DataType {
358 Account = 'account',
359 Product = 'product',
360 }
361​
362 interface Account {
363 name: string
364 }
365 interface Product {
366 code: string
367 }
368​
369 type DataTypeToEntity = {
370 [DataType.Account]: Account
371 [DataType.Product]: Product
372 }
373​
374 const getData = <TDataType extends DataType>(
375 _dataType: TDataType,
376 ): Promise<DataTypeToEntity[TDataType]> =>
377 Promise.resolve({} as DataTypeToEntity[TDataType])
378​
379 const getLabel = <TDataType extends DataType>(
380 _dataType: TDataType,
381 _data: DataTypeToEntity[TDataType],
382 ) => 'test'
383​
384 function Test<TDataType extends DataType>(props: {
385 dataType: TDataType
386 }) {
387 const { data } = useQuery({
388 queryKey: ['test'],
389 queryFn: () => getData(props.dataType),
390 })
391​
392 // Regression guard: this call must compile. With the previous
393 // hand-rolled NoInfer, `data` failed to flow back into the generic
394 // indexed-access parameter `DataTypeToEntity[TDataType]`.
395 return data ? getLabel(props.dataType, data) : null
396 }
397​
398 expectTypeOf(Test).toBeFunction()
399 })
400 })
401})