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

createQueryController.test-d.ts

407 lines12.0 KB

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