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

inject-query.test-d.ts

354 lines11.4 KB

1import { describe, expectTypeOf, it } from 'vitest'
2import { queryKey, sleep } from '@tanstack/query-test-utils'
3import { injectQuery, queryOptions } from '..'
4import type { Signal } from '@angular/core'
5import type { CreateQueryOptions, OmitKeyof, QueryFunction } from '..'
6​
7describe('injectQuery', () => {
8 it('should return the correct types', () => {
9 const key = queryKey()
10 // unspecified query function should default to unknown
11 const noQueryFn = injectQuery(() => ({
12 queryKey: key,
13 }))
14 expectTypeOf(noQueryFn.data()).toEqualTypeOf<unknown>()
15 expectTypeOf(noQueryFn.error()).toEqualTypeOf<Error | null>()
16​
17 // it should infer the result type from the query function
18 const fromQueryFn = injectQuery(() => ({
19 queryKey: key,
20 queryFn: () => 'test',
21 }))
22 expectTypeOf(fromQueryFn.data()).toEqualTypeOf<string | undefined>()
23 expectTypeOf(fromQueryFn.error()).toEqualTypeOf<Error | null>()
24​
25 // it should be possible to specify the result type
26 const withResult = injectQuery<string>(() => ({
27 queryKey: key,
28 queryFn: () => 'test',
29 }))
30 expectTypeOf(withResult.data()).toEqualTypeOf<string | undefined>()
31 expectTypeOf(withResult.error()).toEqualTypeOf<Error | null>()
32​
33 // it should be possible to specify the error type
34 type CustomErrorType = { message: string }
35 const withError = injectQuery<string, CustomErrorType>(() => ({
36 queryKey: key,
37 queryFn: () => 'test',
38 }))
39 expectTypeOf(withError.data()).toEqualTypeOf<string | undefined>()
40 expectTypeOf(withError.error()).toEqualTypeOf<CustomErrorType | null>()
41​
42 // it should infer the result type from the configuration
43 const withResultInfer = injectQuery(() => ({
44 queryKey: key,
45 queryFn: () => true,
46 }))
47 expectTypeOf(withResultInfer.data()).toEqualTypeOf<boolean | undefined>()
48 expectTypeOf(withResultInfer.error()).toEqualTypeOf<Error | null>()
49​
50 // it should be possible to specify a union type as result type
51 const unionTypeSync = injectQuery(() => ({
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 = injectQuery<'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 // it should error when the query function result does not match with the specified type
63 // @ts-expect-error
64 injectQuery<number>(() => ({ queryKey: key, queryFn: () => 'test' }))
65​
66 // it should infer the result type from a generic query function
67 function queryFn<T = string>(): Promise<T> {
68 return Promise.resolve({} as T)
69 }
70​
71 const fromGenericQueryFn = injectQuery(() => ({
72 queryKey: key,
73 queryFn: () => queryFn(),
74 }))
75 expectTypeOf(fromGenericQueryFn.data()).toEqualTypeOf<string | undefined>()
76 expectTypeOf(fromGenericQueryFn.error()).toEqualTypeOf<Error | null>()
77​
78 type MyData = number
79 type MyQueryKey = readonly ['my-data', number]
80​
81 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
82 queryKey: [, n],
83 }) => {
84 return n + 42
85 }
86​
87 const fromMyDataArrayKeyQueryFn = injectQuery(() => ({
88 queryKey: ['my-data', 100] as const,
89 queryFn: getMyDataArrayKey,
90 }))
91 expectTypeOf(fromMyDataArrayKeyQueryFn.data()).toEqualTypeOf<
92 number | undefined
93 >()
94​
95 // it should handle query-functions that return Promise<any>
96 const fromPromiseAnyQueryFn = injectQuery(() => ({
97 queryKey: key,
98 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
99 }))
100 expectTypeOf(fromPromiseAnyQueryFn.data()).toEqualTypeOf<any | undefined>()
101​
102 const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
103 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
104 return Number(context.queryKey[0]) + 42
105 }
106​
107 const fromGetMyDataStringKeyQueryFn = injectQuery(() => ({
108 queryKey: ['1'] as ['1'],
109 queryFn: getMyDataStringKey,
110 }))
111 expectTypeOf(fromGetMyDataStringKeyQueryFn.data()).toEqualTypeOf<
112 number | undefined
113 >()
114​
115 // handles wrapped queries with custom fetcher passed as inline queryFn
116 const createWrappedQuery = <
117 TQueryKey extends [string, Record<string, unknown>?],
118 TQueryFnData,
119 TError,
120 TData = TQueryFnData,
121 >(
122 qk: TQueryKey,
123 fetcher: (
124 obj: TQueryKey[1],
125 token: string,
126 // return type must be wrapped with TQueryFnReturn
127 ) => Promise<TQueryFnData>,
128 options?: OmitKeyof<
129 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
130 'queryKey' | 'queryFn' | 'initialData',
131 'safely'
132 >,
133 ) =>
134 injectQuery(() => ({
135 queryKey: qk,
136 queryFn: () => fetcher(qk[1], 'token'),
137 ...options,
138 }))
139 const fromWrappedQuery = createWrappedQuery([''], () =>
140 Promise.resolve('1'),
141 )
142 expectTypeOf(fromWrappedQuery.data()).toEqualTypeOf<string | undefined>()
143​
144 // handles wrapped queries with custom fetcher passed directly to createQuery
145 const createWrappedFuncStyleQuery = <
146 TQueryKey extends [string, Record<string, unknown>?],
147 TQueryFnData,
148 TError,
149 TData = TQueryFnData,
150 >(
151 qk: TQueryKey,
152 fetcher: () => Promise<TQueryFnData>,
153 options?: OmitKeyof<
154 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
155 'queryKey' | 'queryFn' | 'initialData',
156 'safely'
157 >,
158 ) => injectQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
159 const fromWrappedFuncStyleQuery = createWrappedFuncStyleQuery([''], () =>
160 Promise.resolve(true),
161 )
162 expectTypeOf(fromWrappedFuncStyleQuery.data()).toEqualTypeOf<
163 boolean | undefined
164 >()
165 })
166​
167 describe('initialData', () => {
168 describe('Config object overload', () => {
169 it('should always define TData when initialData is provided as an object', () => {
170 const key = queryKey()
171 const { data } = injectQuery(() => ({
172 queryKey: key,
173 queryFn: () => ({ wow: true }),
174 initialData: { wow: true },
175 }))
176​
177 expectTypeOf(data).toEqualTypeOf<Signal<{ wow: boolean }>>()
178 })
179​
180 it('should define TData when passed through queryOptions', () => {
181 const key = queryKey()
182 const options = () =>
183 queryOptions({
184 queryKey: key,
185 queryFn: () => {
186 return {
187 wow: true,
188 }
189 },
190 initialData: {
191 wow: true,
192 },
193 })
194 const { data } = injectQuery(options)
195​
196 expectTypeOf(data).toEqualTypeOf<Signal<{ wow: boolean }>>()
197 })
198​
199 it('should be possible to define a different TData than TQueryFnData using select with queryOptions spread into useQuery', () => {
200 const key = queryKey()
201 const options = queryOptions({
202 queryKey: key,
203 queryFn: () => Promise.resolve(1),
204 })
205​
206 const query = injectQuery(() => ({
207 ...options,
208 select: (data) => data > 1,
209 }))
210​
211 expectTypeOf(query.data).toEqualTypeOf<Signal<boolean | undefined>>()
212 })
213​
214 it('should always define TData when initialData is provided as a function which ALWAYS returns the data', () => {
215 const key = queryKey()
216 const { data } = injectQuery(() => ({
217 queryKey: key,
218 queryFn: () => {
219 return {
220 wow: true,
221 }
222 },
223 initialData: () => ({
224 wow: true,
225 }),
226 }))
227​
228 expectTypeOf(data).toEqualTypeOf<Signal<{ wow: boolean }>>()
229 })
230​
231 it('should have undefined in the TData union when initialData is NOT provided', () => {
232 const key = queryKey()
233 const { data } = injectQuery(() => ({
234 queryKey: key,
235 queryFn: () => {
236 return {
237 wow: true,
238 }
239 },
240 }))
241​
242 expectTypeOf(data).toEqualTypeOf<Signal<{ wow: boolean } | undefined>>()
243 })
244​
245 it('should have undefined in the TData union when initialData is provided as a function which can return undefined', () => {
246 const key = queryKey()
247 const { data } = injectQuery(() => ({
248 queryKey: key,
249 queryFn: () => {
250 return {
251 wow: true,
252 }
253 },
254 initialData: () => undefined as { wow: boolean } | undefined,
255 }))
256​
257 expectTypeOf(data).toEqualTypeOf<Signal<{ wow: boolean } | undefined>>()
258 })
259​
260 it('should narrow TData after an isSuccess check when initialData is provided as a function which can return undefined', () => {
261 const key = queryKey()
262 const query = injectQuery(() => ({
263 queryKey: key,
264 queryFn: () => {
265 return {
266 wow: true,
267 }
268 },
269 initialData: () => undefined as { wow: boolean } | undefined,
270 }))
271​
272 if (query.isSuccess()) {
273 expectTypeOf(query.data).toEqualTypeOf<Signal<{ wow: boolean }>>()
274 }
275 })
276 })
277​
278 describe('structuralSharing', () => {
279 it('should be able to use structuralSharing with unknown types', () => {
280 const key = queryKey()
281 // https://github.com/TanStack/query/issues/6525#issuecomment-1938411343
282 injectQuery(() => ({
283 queryKey: key,
284 queryFn: () => 5,
285 structuralSharing: (oldData, newData) => {
286 expectTypeOf(oldData).toBeUnknown()
287 expectTypeOf(newData).toBeUnknown()
288 return newData
289 },
290 }))
291 })
292 })
293 })
294​
295 describe('Discriminated union return type', () => {
296 it('should have possibly undefined data by default', () => {
297 const key = queryKey()
298 const query = injectQuery(() => ({
299 queryKey: key,
300 queryFn: () => sleep(0).then(() => 'Some data'),
301 }))
302​
303 expectTypeOf(query.data).toEqualTypeOf<Signal<string | undefined>>()
304 })
305​
306 it('should have defined data when query is success', () => {
307 const key = queryKey()
308 const query = injectQuery(() => ({
309 queryKey: key,
310 queryFn: () => sleep(0).then(() => 'Some data'),
311 }))
312​
313 if (query.isSuccess()) {
314 expectTypeOf(query.data).toEqualTypeOf<Signal<string>>()
315 }
316 })
317​
318 it('should have null error when query is success', () => {
319 const key = queryKey()
320 const query = injectQuery(() => ({
321 queryKey: key,
322 queryFn: () => sleep(0).then(() => 'Some data'),
323 }))
324​
325 if (query.isSuccess()) {
326 expectTypeOf(query.error).toEqualTypeOf<Signal<null>>()
327 }
328 })
329​
330 it('should have undefined data when query is pending', () => {
331 const key = queryKey()
332 const query = injectQuery(() => ({
333 queryKey: key,
334 queryFn: () => sleep(0).then(() => 'Some data'),
335 }))
336​
337 if (query.isPending()) {
338 expectTypeOf(query.data).toEqualTypeOf<Signal<undefined>>()
339 }
340 })
341​
342 it('should have defined error when query is error', () => {
343 const key = queryKey()
344 const query = injectQuery(() => ({
345 queryKey: key,
346 queryFn: () => sleep(0).then(() => 'Some data'),
347 }))
348​
349 if (query.isError()) {
350 expectTypeOf(query.error).toEqualTypeOf<Signal<Error>>()
351 }
352 })
353 })
354})