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