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

useQuery.test-d.tsx

354 lines10.8 KB

1import { createKey } from '@tanstack/query-test-utils'
2import { assertType, 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 = createKey()
10​
11 it('should default to unknown when the query function is unspecified', () => {
12 const noQueryFn = useQuery({ queryKey: key })
13 expectTypeOf(noQueryFn.data).toEqualTypeOf<unknown>()
14 expectTypeOf(noQueryFn.error).toEqualTypeOf<Error | null>()
15 })
16​
17 it('should infer the result type from the query function', () => {
18 const fromQueryFn = useQuery({ queryKey: key, queryFn: () => 'test' })
19 expectTypeOf(fromQueryFn.data).toEqualTypeOf<string | undefined>()
20 expectTypeOf(fromQueryFn.error).toEqualTypeOf<Error | null>()
21 expectTypeOf(fromQueryFn).not.toHaveProperty('promise')
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: () => Promise.resolve(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 Promise.resolve(n + 42)
94 }
95​
96 useQuery({
97 queryKey: ['my-data', 100],
98 queryFn: getMyDataArrayKey,
99 })
100​
101 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
102 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
103 return Promise.resolve(Number(context.queryKey[0]) + 42)
104 }
105​
106 useQuery({
107 queryKey: ['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 >,
137 ) =>
138 useQuery({
139 queryKey: qk,
140 queryFn: () => fetcher(qk[1], 'token'),
141 ...options,
142 })
143 const testQuery = useWrappedQuery([''], () => Promise.resolve('1'))
144 expectTypeOf(testQuery.data).toEqualTypeOf<string | undefined>()
145 })
146​
147 it('should handle wrapped queries with custom fetcher passed directly to useQuery', () => {
148 const useWrappedFuncStyleQuery = <
149 TQueryKey extends [string, Record<string, unknown>?],
150 TQueryFnData,
151 TError,
152 TData = TQueryFnData,
153 >(
154 qk: TQueryKey,
155 fetcher: () => Promise<TQueryFnData>,
156 options?: OmitKeyof<
157 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
158 'queryKey' | 'queryFn' | 'initialData'
159 >,
160 ) => useQuery({ queryKey: qk, queryFn: fetcher, ...options })
161 const testFuncStyle = useWrappedFuncStyleQuery([''], () =>
162 Promise.resolve(true),
163 )
164 expectTypeOf(testFuncStyle.data).toEqualTypeOf<boolean | undefined>()
165 })
166​
167 it('should return the correct states for a successful query', () => {
168 const state = useQuery<string, Error>({
169 queryKey: key,
170 queryFn: () => Promise.resolve('test'),
171 })
172​
173 if (state.isPending) {
174 expectTypeOf(state.data).toEqualTypeOf<undefined>()
175 expectTypeOf(state.error).toEqualTypeOf<null>()
176 return <span>pending</span>
177 }
178​
179 if (state.isLoadingError) {
180 expectTypeOf(state.data).toEqualTypeOf<undefined>()
181 expectTypeOf(state.error).toEqualTypeOf<Error>()
182 return <span>{state.error.message}</span>
183 }
184​
185 expectTypeOf(state.data).toEqualTypeOf<string>()
186 expectTypeOf(state.error).toEqualTypeOf<Error | null>()
187 return <span>{state.data}</span>
188 })
189​
190 describe('initialData', () => {
191 describe('Config object overload', () => {
192 it('should always define TData when initialData is provided as an object', () => {
193 const { data } = useQuery({
194 queryKey: createKey(),
195 queryFn: () => ({ wow: true }),
196 initialData: { wow: true },
197 })
198​
199 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
200 })
201​
202 it('should define TData when passed through queryOptions', () => {
203 const options = queryOptions({
204 queryKey: createKey(),
205 queryFn: () => {
206 return {
207 wow: true,
208 }
209 },
210 initialData: {
211 wow: true,
212 },
213 })
214 const { data } = useQuery(options)
215​
216 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
217 })
218​
219 it('should be possible to define a different TData than TQueryFnData using select with queryOptions spread into useQuery', () => {
220 const options = queryOptions({
221 queryKey: createKey(),
222 queryFn: () => Promise.resolve(1),
223 })
224​
225 const query = useQuery({
226 ...options,
227 select: (data) => data > 1,
228 })
229​
230 expectTypeOf(query.data).toEqualTypeOf<boolean | undefined>()
231 })
232​
233 it('should always define TData when initialData is provided as a function which ALWAYS returns the data', () => {
234 const { data } = useQuery({
235 queryKey: createKey(),
236 queryFn: () => {
237 return {
238 wow: true,
239 }
240 },
241 initialData: () => ({
242 wow: true,
243 }),
244 })
245​
246 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
247 })
248​
249 it('should have undefined in the TData union when initialData is NOT provided', () => {
250 const { data } = useQuery({
251 queryKey: createKey(),
252 queryFn: () => {
253 return {
254 wow: true,
255 }
256 },
257 })
258​
259 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
260 })
261​
262 it('should have undefined in the TData union when initialData is provided as a function which can return undefined', () => {
263 const { data } = useQuery({
264 queryKey: createKey(),
265 queryFn: () => {
266 return {
267 wow: true,
268 }
269 },
270 initialData: () => undefined as { wow: boolean } | undefined,
271 })
272​
273 expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
274 })
275​
276 it('should narrow TData after an isSuccess check when initialData is provided as a function which can return undefined', () => {
277 const { data, isSuccess } = useQuery({
278 queryKey: createKey(),
279 queryFn: () => {
280 return {
281 wow: true,
282 }
283 },
284 initialData: () => undefined as { wow: boolean } | undefined,
285 })
286​
287 if (isSuccess) {
288 expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
289 }
290 })
291​
292 it('should not have undefined in data when initialData is provided', () => {
293 const { data } = useQuery({
294 queryKey: createKey(),
295 initialData: 42,
296 })
297​
298 expectTypeOf(data).toEqualTypeOf<number>()
299 })
300 })
301​
302 it('should preserve discriminated-union narrowing', () => {
303 type Result =
304 | { type: 'first'; first: string }
305 | { type: 'second'; second: string }
306​
307 const query = useQuery({
308 queryKey: createKey(),
309 queryFn: (): Result => ({ type: 'first', first: 'a' }),
310 })
311​
312 const second = query.data?.type === 'first' ? undefined : query.data
313​
314 expectTypeOf(second).toEqualTypeOf<
315 { type: 'second'; second: string } | undefined
316 >()
317 })
318​
319 describe('custom hook', () => {
320 it('should allow custom hooks using UseQueryOptions', () => {
321 type Data = string
322​
323 const useCustomQuery = (
324 options?: OmitKeyof<UseQueryOptions<Data>, 'queryKey' | 'queryFn'>,
325 ) => {
326 return useQuery({
327 ...options,
328 queryKey: createKey(),
329 queryFn: () => Promise.resolve('data'),
330 })
331 }
332​
333 const { data } = useCustomQuery()
334​
335 expectTypeOf(data).toEqualTypeOf<Data | undefined>()
336 })
337 })
338​
339 describe('structuralSharing', () => {
340 it('should be able to use structuralSharing with unknown types', () => {
341 // https://github.com/TanStack/query/issues/6525#issuecomment-1938411343
342 useQuery({
343 queryKey: createKey(),
344 queryFn: () => 5,
345 structuralSharing: (oldData, newData) => {
346 expectTypeOf(oldData).toBeUnknown()
347 expectTypeOf(newData).toBeUnknown()
348 return newData
349 },
350 })
351 })
352 })
353 })
354})