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

utils.test-d.tsx

891 lines26.3 KB

1import { assertType, describe, expectTypeOf, it } from 'vitest'
2import { QueryClient } from '../queryClient'
3import {
4 addConsumeAwareSignal,
5 addToEnd,
6 addToStart,
7 ensureQueryFn,
8 functionalUpdate,
9 hashKey,
10 hashQueryKeyByOptions,
11 isPlainArray,
12 isPlainObject,
13 isServer,
14 isValidTimeout,
15 keepPreviousData,
16 matchMutation,
17 matchQuery,
18 noop,
19 partialMatchKey,
20 replaceData,
21 replaceEqualDeep,
22 resolveQueryValue,
23 shallowEqualObjects,
24 shouldThrowError,
25 skipToken,
26 sleep,
27 timeUntilStale,
28} from '../utils'
29import type {
30 MutationFilters,
31 QueryFilters,
32 QueryTypeFilter,
33 SkipToken,
34 Updater,
35} from '../utils'
36import type { Mutation } from '../mutation'
37import type { Query } from '../query'
38import type {
39 DataTag,
40 MutationStatus,
41 QueryFunction,
42 QueryKey,
43 QueryOptions,
44} from '../types'
45​
46class CustomError extends Error {
47 override name = 'CustomError' as const
49​
50describe('QueryFilters', () => {
51 it('should be typed unknown even if tagged generics are passed', () => {
52 type TData = { a: number; b: string }
53 type TError = Error & { message: string }
54​
55 const filters: QueryFilters<DataTag<QueryKey, TData, TError>> = {
56 predicate(query) {
57 expectTypeOf(query.setData({ a: 1, b: '1' })).toEqualTypeOf<unknown>()
58 return true
59 },
60 queryKey: ['key'] as DataTag<undefined, TData, TError>,
61 }
62​
63 const queryClient = new QueryClient()
64​
65 const data = queryClient.getQueryData(filters.queryKey!)
66 expectTypeOf(data).toEqualTypeOf<TData | undefined>()
67​
68 const error = queryClient.getQueryState(filters.queryKey!)?.error
69 expectTypeOf(error).toEqualTypeOf<TError | null | undefined>()
70 })
71​
72 it('should be loose typed if generics are defaults', () => {
73 const a: QueryFilters = {
74 predicate(query) {
75 expectTypeOf(query.setData({ a: 1, b: '1' })).toEqualTypeOf<unknown>()
76 return true
77 },
78 queryKey: ['key'],
79 }
80​
81 const queryClient = new QueryClient()
82 const data = queryClient.getQueryData(a.queryKey!)
83 expectTypeOf(data).toEqualTypeOf<unknown>()
84​
85 const error = queryClient.getQueryState(a.queryKey!)?.error
86 expectTypeOf(error).toEqualTypeOf<Error | null | undefined>()
87 })
88​
89 it('should allow a partial query key to be passed', () => {
90 const filters: QueryFilters<readonly ['key', { a: number; b: string }]> = {
91 queryKey: ['key'],
92 }
93​
94 expectTypeOf(filters.queryKey).toEqualTypeOf<
95 | undefined
96 | readonly []
97 | readonly ['key']
98 | readonly [
99 'key',
100 {
101 a: number
102 b: string
103 },
104 ]
105 >()
106 })
107​
108 it('should work with readonly union types', () => {
109 const filters: QueryFilters<
110 readonly ['key'] | readonly ['key', 'something']
111 > = {
112 queryKey: ['key'],
113 }
114​
115 expectTypeOf(filters.queryKey).toEqualTypeOf<
116 undefined | readonly [] | readonly ['key'] | readonly ['key', 'something']
117 >()
118 })
119​
120 // we test that there are not type errors here
121 // oxlint-disable-next-line vitest/expect-expect
122 it('should work with unions of different lengths', () => {
123 type Key =
124 | readonly ['foo']
125 | readonly ['foo', 'bar']
126 | readonly ['foo', 'bar', 'baz']
127​
128 const queryKey: Key = ['foo', 'bar'] as any as Key
129​
130 new QueryClient().invalidateQueries({ queryKey })
131 })
132​
133 it('should error on invalid query keys', () => {
134 assertType<QueryFilters<readonly ['key', { a: number; b: string }]>>({
135 // @ts-expect-error cannot pass invalid query key
136 queryKey: ['invalid', { a: 1, b: '1' }],
137 })
138 })
139​
140 it('should type every filter as optional', () => {
141 expectTypeOf<QueryFilters>().toEqualTypeOf<{
142 type?: QueryTypeFilter
143 exact?: boolean
144 predicate?: (query: Query) => boolean
145 queryKey?: QueryKey | ReadonlyArray<unknown>
146 stale?: boolean
147 fetchStatus?: 'fetching' | 'paused' | 'idle'
148 }>()
149 })
150​
151 it('should keep every filter writable', () => {
152 // stripping `readonly` from every key must be a no-op
153 expectTypeOf<{
154 -readonly [Key in keyof QueryFilters]: QueryFilters[Key]
155 }>().toEqualTypeOf<QueryFilters>()
156​
157 const filters: QueryFilters = {}
158​
159 filters.type = 'active'
160 filters.exact = true
161 filters.predicate = () => true
162 filters.queryKey = ['key']
163 filters.stale = true
164 filters.fetchStatus = 'idle'
165 })
166​
167 it('should default TQueryKey to QueryKey', () => {
168 expectTypeOf<QueryFilters>().toEqualTypeOf<QueryFilters<QueryKey>>()
169 expectTypeOf<QueryFilters['queryKey']>().toEqualTypeOf<
170 ReadonlyArray<unknown> | undefined
171 >()
172 })
173​
174 it('should constrain TQueryKey to QueryKey', () => {
175 expectTypeOf<QueryFilters<readonly ['key']>['queryKey']>().toEqualTypeOf<
176 undefined | readonly [] | readonly ['key']
177 >()
178​
179 assertType<
180 // @ts-expect-error a non-array type does not satisfy the QueryKey constraint
181 QueryFilters<{ key: string }>
182 >({})
183 })
184​
185 it('should type predicate with an untyped Query regardless of TQueryKey', () => {
186 expectTypeOf<NonNullable<QueryFilters<readonly ['key']>['predicate']>>()
187 .parameter(0)
188 .toEqualTypeOf<Query>()
189​
190 expectTypeOf<NonNullable<QueryFilters['predicate']>>()
191 .parameter(0)
192 .toEqualTypeOf<Query<unknown, Error, unknown, ReadonlyArray<unknown>>>()
193 })
194​
195 it('should type fetchStatus as FetchStatus', () => {
196 expectTypeOf<QueryFilters['fetchStatus']>().toEqualTypeOf<
197 'fetching' | 'paused' | 'idle' | undefined
198 >()
199​
200 assertType<QueryFilters>({
201 // @ts-expect-error 'success' is not a FetchStatus
202 fetchStatus: 'success',
203 })
204 })
205​
206 describe('type', () => {
207 it('should be typed as QueryTypeFilter', () => {
208 expectTypeOf<Pick<QueryFilters, 'type'>>().toEqualTypeOf<{
209 type?: 'all' | 'active' | 'inactive'
210 }>()
211​
212 assertType<QueryFilters>({
213 // @ts-expect-error 'stale' is not a QueryTypeFilter
214 type: 'stale',
215 })
216 })
217 })
218​
219 describe('exact', () => {
220 it('should be typed as an optional boolean', () => {
221 expectTypeOf<Pick<QueryFilters, 'exact'>>().toEqualTypeOf<{
222 exact?: boolean
223 }>()
224​
225 assertType<QueryFilters>({
226 // @ts-expect-error exact must be a boolean
227 exact: 'yes',
228 })
229 })
230 })
231​
232 describe('stale', () => {
233 it('should be typed as an optional boolean', () => {
234 expectTypeOf<Pick<QueryFilters, 'stale'>>().toEqualTypeOf<{
235 stale?: boolean
236 }>()
237​
238 assertType<QueryFilters>({
239 // @ts-expect-error stale must be a boolean
240 stale: 'yes',
241 })
242 })
243 })
244})
245​
246describe('MutationFilters', () => {
247 it('should type every filter as optional', () => {
248 expectTypeOf<MutationFilters>().toEqualTypeOf<{
249 exact?: boolean
250 predicate?: (mutation: Mutation) => boolean
251 mutationKey?: ReadonlyArray<unknown>
252 status?: MutationStatus
253 }>()
254 })
255​
256 it('should keep every filter writable', () => {
257 // stripping `readonly` from every key must be a no-op
258 expectTypeOf<{
259 -readonly [Key in keyof MutationFilters]: MutationFilters[Key]
260 }>().toEqualTypeOf<MutationFilters>()
261​
262 const filters: MutationFilters = {}
263​
264 filters.exact = true
265 filters.predicate = () => true
266 filters.mutationKey = ['key']
267 filters.status = 'success'
268 })
269​
270 it('should default TData to unknown and TError to DefaultError', () => {
271 expectTypeOf<NonNullable<MutationFilters['predicate']>>()
272 .parameter(0)
273 .toEqualTypeOf<Mutation<unknown, Error, unknown, unknown>>()
274 })
275​
276 it('should default TVariables and TOnMutateResult to unknown', () => {
277 expectTypeOf<
278 NonNullable<MutationFilters<number, CustomError>['predicate']>
279 >()
280 .parameter(0)
281 .toEqualTypeOf<Mutation<number, CustomError, unknown, unknown>>()
282 })
283​
284 it('should forward TVariables into the predicate mutation', () => {
285 const filters: MutationFilters<number, CustomError, string> = {
286 predicate(mutation) {
287 expectTypeOf(mutation).toEqualTypeOf<
288 Mutation<number, CustomError, string, unknown>
289 >()
290 expectTypeOf(mutation.state.variables).toEqualTypeOf<
291 string | undefined
292 >()
293 return true
294 },
295 }
296​
297 expectTypeOf(filters.predicate).toEqualTypeOf<
298 | ((mutation: Mutation<number, CustomError, string, unknown>) => boolean)
299 | undefined
300 >()
301 })
302​
303 it('should forward TOnMutateResult into the predicate mutation', () => {
304 const filters: MutationFilters<
305 number,
306 CustomError,
307 string,
308 { rollback: () => void }
309 > = {
310 predicate(mutation) {
311 expectTypeOf(mutation).toEqualTypeOf<
312 Mutation<number, CustomError, string, { rollback: () => void }>
313 >()
314 expectTypeOf(mutation.state.context).toEqualTypeOf<
315 { rollback: () => void } | undefined
316 >()
317 return true
318 },
319 }
320​
321 expectTypeOf(filters.predicate).toEqualTypeOf<
322 | ((
323 mutation: Mutation<
324 number,
325 CustomError,
326 string,
327 { rollback: () => void }
328 >,
329 ) => boolean)
330 | undefined
331 >()
332 })
333​
334 it('should forward TData and TError into the predicate mutation state', () => {
335 const filters: MutationFilters<number, CustomError> = {
336 predicate(mutation) {
337 expectTypeOf(mutation.state.data).toEqualTypeOf<number | undefined>()
338 expectTypeOf(mutation.state.error).toEqualTypeOf<CustomError | null>()
339 return true
340 },
341 }
342​
343 expectTypeOf(filters.predicate).toEqualTypeOf<
344 | ((mutation: Mutation<number, CustomError, unknown, unknown>) => boolean)
345 | undefined
346 >()
347 })
348​
349 it('should not parameterize mutationKey by any generic, unlike QueryFilters', () => {
350 // `QueryFilters.queryKey` narrows with TQueryKey, but `MutationFilters` has
351 // no key generic at all: `mutationKey` is always the prefixes of `MutationKey`
352 expectTypeOf<
353 MutationFilters<number, CustomError, string, void>['mutationKey']
354 >().toEqualTypeOf<ReadonlyArray<unknown> | undefined>()
355​
356 expectTypeOf<MutationFilters['mutationKey']>().toEqualTypeOf<
357 MutationFilters<number>['mutationKey']
358 >()
359​
360 // any MutationKey is therefore accepted, whatever the generics are
361 assertType<MutationFilters<number, CustomError, string, void>>({
362 mutationKey: ['anything', { at: 'all' }, 1],
363 })
364 })
365​
366 it('should type status as MutationStatus', () => {
367 expectTypeOf<MutationFilters['status']>().toEqualTypeOf<
368 'idle' | 'pending' | 'success' | 'error' | undefined
369 >()
370​
371 assertType<MutationFilters>({
372 // @ts-expect-error 'fetching' is not a MutationStatus
373 status: 'fetching',
374 })
375 })
376})
377​
378describe('QueryTypeFilter', () => {
379 it('should be a union of the three query types', () => {
380 expectTypeOf<QueryTypeFilter>().toEqualTypeOf<
381 'all' | 'active' | 'inactive'
382 >()
383 })
384})
385​
386describe('Updater', () => {
387 it('should be a union of the value and the updater function', () => {
388 expectTypeOf<Updater<number, string>>().toEqualTypeOf<
389 string | ((input: number) => string)
390 >()
391 })
392​
393 it('should accept both branches for the same instantiation', () => {
394 const value: Updater<number, string> = 'next'
395 const fn: Updater<number, string> = (input) => {
396 // the annotation alone contextually types the parameter as TInput
397 expectTypeOf(input).toEqualTypeOf<number>()
398 return String(input)
399 }
400​
401 // the annotation narrows each variable down to the branch it was given
402 expectTypeOf(value).toEqualTypeOf<string>()
403 expectTypeOf(fn).toEqualTypeOf<(input: number) => string>()
404 })
405​
406 it('should keep the value branch assignable but not callable', () => {
407 expectTypeOf<
408 Exclude<Updater<number, string>, Function>
409 >().toEqualTypeOf<string>()
410​
411 // @ts-expect-error the value branch is not a function
412 const _fn: Extract<Updater<number, string>, string> = (input: number) =>
413 String(input)
414 })
415​
416 it('should type the function branch input as TInput and output as TOutput', () => {
417 type UpdaterFn = Extract<Updater<number, string>, Function>
418​
419 expectTypeOf<UpdaterFn>().parameter(0).toEqualTypeOf<number>()
420 expectTypeOf<UpdaterFn>().returns.toEqualTypeOf<string>()
421 })
422})
423​
424describe('functionalUpdate', () => {
425 it('should type the updater parameter as Updater<TInput, TOutput>', () => {
426 expectTypeOf(functionalUpdate<number, string>)
427 .parameter(0)
428 .toEqualTypeOf<string | ((input: number) => string)>()
429 })
430​
431 it('should type the input parameter as TInput', () => {
432 expectTypeOf(functionalUpdate<number, string>)
433 .parameter(1)
434 .toEqualTypeOf<number>()
435 })
436​
437 it('should return TOutput', () => {
438 expectTypeOf(
439 functionalUpdate<number, string>,
440 ).returns.toEqualTypeOf<string>()
441​
442 const result = functionalUpdate<number, string>((input) => String(input), 1)
443 expectTypeOf(result).toEqualTypeOf<string>()
444 })
445​
446 it('should infer both generics from the value branch', () => {
447 const result = functionalUpdate('next', 1)
448 expectTypeOf(result).toEqualTypeOf<string>()
449 })
450})
451​
452describe('noop', () => {
453 it('should resolve to the void overload when called', () => {
454 expectTypeOf(noop()).toEqualTypeOf<void>()
455 })
456})
457​
458describe('isValidTimeout', () => {
459 it('should narrow unknown to number', () => {
460 const value: unknown = 1
461​
462 if (isValidTimeout(value)) {
463 expectTypeOf(value).toEqualTypeOf<number>()
464 } else {
465 expectTypeOf(value).toEqualTypeOf<unknown>()
466 }
467 })
468​
469 it('should accept unknown as its parameter', () => {
470 expectTypeOf(isValidTimeout).parameter(0).toEqualTypeOf<unknown>()
471 expectTypeOf(isValidTimeout).returns.toEqualTypeOf<boolean>()
472 })
473})
474​
475describe('isPlainArray', () => {
476 it('should narrow unknown to Array<unknown>', () => {
477 const value: unknown = []
478​
479 if (isPlainArray(value)) {
480 expectTypeOf(value).toEqualTypeOf<Array<unknown>>()
481 } else {
482 expectTypeOf(value).toEqualTypeOf<unknown>()
483 }
484 })
485​
486 it('should accept unknown as its parameter', () => {
487 expectTypeOf(isPlainArray).parameter(0).toEqualTypeOf<unknown>()
488 })
489})
490​
491describe('isPlainObject', () => {
492 it('should narrow unknown to Record<PropertyKey, unknown>', () => {
493 const value: unknown = {}
494​
495 if (isPlainObject(value)) {
496 expectTypeOf(value).toEqualTypeOf<Record<PropertyKey, unknown>>()
497 } else {
498 expectTypeOf(value).toEqualTypeOf<unknown>()
499 }
500 })
501​
502 it('should accept any as its parameter, unlike the other guards', () => {
503 expectTypeOf(isPlainObject).parameter(0).toBeAny()
504 })
505})
506​
507describe('partialMatchKey', () => {
508 it('should only expose the QueryKey overload, not the any implementation', () => {
509 expectTypeOf(partialMatchKey)
510 .parameter(0)
511 .toEqualTypeOf<ReadonlyArray<unknown>>()
512 expectTypeOf(partialMatchKey)
513 .parameter(1)
514 .toEqualTypeOf<ReadonlyArray<unknown>>()
515 expectTypeOf(partialMatchKey).returns.toEqualTypeOf<boolean>()
516​
517 expectTypeOf(partialMatchKey(['a'], ['a'])).toEqualTypeOf<boolean>()
518 // @ts-expect-error a non-QueryKey argument is rejected
519 partialMatchKey(1, 2)
520 })
521})
522​
523describe('hashKey', () => {
524 it('should only accept an array key', () => {
525 // `QueryKey | MutationKey` collapses to a single type here: with an empty
526 // `Register`, both resolve to `ReadonlyArray<unknown>`, so the declared
527 // union is structurally indistinguishable from either member alone.
528 expectTypeOf(hashKey).parameter(0).toEqualTypeOf<ReadonlyArray<unknown>>()
529​
530 // @ts-expect-error a non-array key is rejected
531 hashKey('a')
532 })
533​
534 it('should return a string', () => {
535 expectTypeOf(hashKey).returns.toEqualTypeOf<string>()
536 })
537})
538​
539describe('hashQueryKeyByOptions', () => {
540 it('should accept the options argument optionally', () => {
541 expectTypeOf(hashQueryKeyByOptions(['a'])).toEqualTypeOf<string>()
542 expectTypeOf(
543 hashQueryKeyByOptions(['a'], { queryKeyHashFn: hashKey }),
544 ).toEqualTypeOf<string>()
545 })
546})
547​
548describe('resolveQueryValue', () => {
549 it('should default TData to TQueryFnData', () => {
550 const query = {} as Query<number, Error, number, readonly ['key']>
551​
552 resolveQueryValue<string, number>((q) => {
553 expectTypeOf(q).toEqualTypeOf<
554 Query<number, Error, number, ReadonlyArray<unknown>>
555 >()
556 return 'value'
557 }, query as never)
558 })
559​
560 it('should widen the return type with undefined', () => {
561 const query = {} as Query<number, Error, number, readonly ['key']>
562​
563 const value = resolveQueryValue<
564 string,
565 number,
566 Error,
567 number,
568 readonly ['key']
569 >('value', query)
570 expectTypeOf(value).toEqualTypeOf<string | undefined>()
571 })
572​
573 it('should type the query parameter with every generic', () => {
574 expectTypeOf(
575 resolveQueryValue<string, number, CustomError, boolean, readonly ['key']>,
576 )
577 .parameter(1)
578 .toEqualTypeOf<Query<number, CustomError, boolean, readonly ['key']>>()
579 })
580​
581 it('should accept both a plain value and a resolver function', () => {
582 const query = {} as Query<number, Error, number, readonly ['key']>
583​
584 const fromFn = resolveQueryValue<
585 string,
586 number,
587 Error,
588 number,
589 readonly ['key']
590 >((q) => {
591 expectTypeOf(q).toEqualTypeOf<
592 Query<number, Error, number, readonly ['key']>
593 >()
594 return 'value'
595 }, query)
596 expectTypeOf(fromFn).toEqualTypeOf<string | undefined>()
597​
598 const fromUndefined = resolveQueryValue<
599 string,
600 number,
601 Error,
602 number,
603 readonly ['key']
604 >(undefined, query)
605 expectTypeOf(fromUndefined).toEqualTypeOf<string | undefined>()
606 })
607})
608​
609describe('matchQuery', () => {
610 it('should accept a QueryFilters and any Query', () => {
611 expectTypeOf(matchQuery).parameter(0).toEqualTypeOf<QueryFilters>()
612 expectTypeOf(matchQuery).returns.toEqualTypeOf<boolean>()
613​
614 expectTypeOf(
615 matchQuery({ queryKey: ['a'] }, {} as Query<number, Error>),
616 ).toEqualTypeOf<boolean>()
617 })
618})
619​
620describe('matchMutation', () => {
621 it('should accept a MutationFilters and any Mutation', () => {
622 expectTypeOf(matchMutation).parameter(0).toEqualTypeOf<MutationFilters>()
623 expectTypeOf(matchMutation).returns.toEqualTypeOf<boolean>()
624​
625 expectTypeOf(
626 matchMutation({ mutationKey: ['a'] }, {} as Mutation<number, Error>),
627 ).toEqualTypeOf<boolean>()
628 })
629})
630​
631describe('replaceEqualDeep', () => {
632 it('should return the type of b and not relate it to a', () => {
633 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
634 const result = replaceEqualDeep({ a: 1 } as unknown, { b: '1' })
635 expectTypeOf(result).toEqualTypeOf<{ b: string }>()
636​
637 expectTypeOf(replaceEqualDeep<number>)
638 .parameter(0)
639 .toEqualTypeOf<unknown>()
640 expectTypeOf(replaceEqualDeep<number>)
641 .parameter(1)
642 .toEqualTypeOf<number>()
643 })
644​
645 it('should accept the depth argument optionally', () => {
646 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
647 expectTypeOf(replaceEqualDeep(1 as unknown, 2)).toEqualTypeOf<number>()
648 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
649 expectTypeOf(replaceEqualDeep(1 as unknown, 2, 0)).toEqualTypeOf<number>()
650 })
651})
652​
653describe('shallowEqualObjects', () => {
654 it('should allow b to be undefined but not a', () => {
655 expectTypeOf(shallowEqualObjects<{ a: number }>)
656 .parameter(0)
657 .toEqualTypeOf<{ a: number }>()
658 expectTypeOf(shallowEqualObjects<{ a: number }>)
659 .parameter(1)
660 .toEqualTypeOf<{ a: number } | undefined>()
661​
662 expectTypeOf(
663 shallowEqualObjects({ a: 1 }, undefined),
664 ).toEqualTypeOf<boolean>()
665 // @ts-expect-error a cannot be undefined
666 shallowEqualObjects(undefined, { a: 1 })
667 })
668​
669 it('should constrain T to a record', () => {
670 expectTypeOf(
671 shallowEqualObjects({ a: 1 }, { a: 1 }),
672 ).toEqualTypeOf<boolean>()
673 // @ts-expect-error a primitive does not satisfy Record<string, any>
674 shallowEqualObjects(1, 1)
675 })
676})
677​
678describe('keepPreviousData', () => {
679 it('should return the previous data widened with undefined', () => {
680 expectTypeOf(keepPreviousData<string>('x')).toEqualTypeOf<
681 string | undefined
682 >()
683 expectTypeOf(keepPreviousData<string>)
684 .parameter(0)
685 .toEqualTypeOf<string | undefined>()
686 })
687})
688​
689describe('addToEnd', () => {
690 it('should return a mutable Array<T>', () => {
691 const result = addToEnd([1, 2], 3)
692 expectTypeOf(result).toEqualTypeOf<Array<number>>()
693​
694 // the result is mutable, so push is available
695 result.push(4)
696 })
697​
698 it('should accept the max argument optionally', () => {
699 expectTypeOf(addToEnd([1], 2)).toEqualTypeOf<Array<number>>()
700 expectTypeOf(addToEnd([1], 2, 5)).toEqualTypeOf<Array<number>>()
701 })
702​
703 it('should reject a readonly array of items', () => {
704 const items: ReadonlyArray<number> = [1, 2]
705 expectTypeOf(addToEnd([...items], 3)).toEqualTypeOf<Array<number>>()
706 // @ts-expect-error a readonly array is not assignable to Array<T>
707 addToEnd(items, 3)
708 })
709})
710​
711describe('addToStart', () => {
712 it('should return a mutable Array<T>', () => {
713 const result = addToStart([1, 2], 3)
714 expectTypeOf(result).toEqualTypeOf<Array<number>>()
715​
716 result.push(4)
717 })
718​
719 it('should reject a readonly array of items', () => {
720 const items: ReadonlyArray<number> = [1, 2]
721 expectTypeOf(addToStart([...items], 3)).toEqualTypeOf<Array<number>>()
722 // @ts-expect-error a readonly array is not assignable to Array<T>
723 addToStart(items, 3)
724 })
725})
726​
727describe('skipToken', () => {
728 it('should be a unique symbol, not the widened symbol type', () => {
729 expectTypeOf(skipToken).toEqualTypeOf<SkipToken>()
730 expectTypeOf(skipToken).not.toEqualTypeOf<symbol>()
731​
732 // the sentinel narrows to itself, so a plain symbol is not assignable to it
733 const plainSymbol: symbol = skipToken
734 expectTypeOf(plainSymbol).toEqualTypeOf<symbol>()
735​
736 // @ts-expect-error a plain symbol is not the skipToken sentinel
737 assertType<SkipToken>(plainSymbol)
738 })
739})
740​
741describe('ensureQueryFn', () => {
742 it('should accept a SkipToken in queryFn but never return one', () => {
743 const queryFn = skipToken as
744 | QueryFunction<number, readonly ['key']>
745 | SkipToken
746​
747 expectTypeOf<
748 Parameters<typeof ensureQueryFn<number, readonly ['key']>>[0]['queryFn']
749 >().toEqualTypeOf<
750 QueryFunction<number, readonly ['key']> | SkipToken | undefined
751 >()
752​
753 const resolved = ensureQueryFn<number, readonly ['key']>({ queryFn })
754 expectTypeOf(resolved).toEqualTypeOf<
755 QueryFunction<number, readonly ['key']>
756 >()
757 })
758​
759 it('should accept the fetchOptions argument optionally', () => {
760 expectTypeOf(ensureQueryFn<number, readonly ['key']>({})).toEqualTypeOf<
761 QueryFunction<number, readonly ['key']>
762 >()
763 })
764​
765 it('should only read queryFn and queryHash from the options', () => {
766 expectTypeOf<
767 Parameters<typeof ensureQueryFn<number, readonly ['key']>>[0]
768 >().toEqualTypeOf<{
769 queryFn?: QueryFunction<number, readonly ['key']> | SkipToken
770 queryHash?: string
771 }>()
772 })
773})
774​
775describe('shouldThrowError', () => {
776 it('should tie params to the parameters of the throwOnError function', () => {
777 type ThrowOnError = (error: CustomError, query: Query) => boolean
778​
779 expectTypeOf(shouldThrowError<ThrowOnError>)
780 .parameter(1)
781 .toEqualTypeOf<[error: CustomError, query: Query]>()
782​
783 expectTypeOf(
784 shouldThrowError<ThrowOnError>,
785 ).returns.toEqualTypeOf<boolean>()
786 })
787​
788 it('should constrain the throwOnError function to one returning a boolean', () => {
789 expectTypeOf(
790 shouldThrowError<(error: CustomError) => boolean>(
791 (_error) => true,
792 [new CustomError()],
793 ),
794 ).toEqualTypeOf<boolean>()
795​
796 shouldThrowError<
797 // @ts-expect-error a throwOnError function has to return a boolean
798 (error: CustomError) => unknown
799 >((_error) => undefined, [new CustomError()])
800 })
801​
802 it('should accept a boolean or undefined as throwOnError', () => {
803 type ThrowOnError = (error: CustomError) => boolean
804​
805 expectTypeOf(shouldThrowError<ThrowOnError>)
806 .parameter(0)
807 .toEqualTypeOf<boolean | ThrowOnError | undefined>()
808​
809 expectTypeOf(
810 shouldThrowError<ThrowOnError>(true, [new CustomError()]),
811 ).toEqualTypeOf<boolean>()
812 })
813})
814​
815describe('sleep', () => {
816 it('should return a Promise<void>', () => {
817 expectTypeOf(sleep(1)).toEqualTypeOf<Promise<void>>()
818 expectTypeOf(sleep).parameter(0).toEqualTypeOf<number>()
819 })
820})
821​
822describe('addConsumeAwareSignal', () => {
823 it('should intersect the object with a signal property', () => {
824 const result = addConsumeAwareSignal(
825 { queryKey: ['key'] },
826 () => new AbortController().signal,
827 noop,
828 )
829​
830 expectTypeOf(result).toEqualTypeOf<
831 { queryKey: Array<string> } & { signal: AbortSignal }
832 >()
833 expectTypeOf(result.signal).toEqualTypeOf<AbortSignal>()
834 expectTypeOf(result.queryKey).toEqualTypeOf<Array<string>>()
835 })
836​
837 it('should only accept an onCancelled callback taking no arguments', () => {
838 expectTypeOf(addConsumeAwareSignal<{ a: number }>)
839 .parameter(2)
840 .toEqualTypeOf<VoidFunction>()
841 })
842})
843​
844describe('isServer', () => {
845 it('should be typed as a boolean', () => {
846 expectTypeOf(isServer).toEqualTypeOf<boolean>()
847 })
848})
849​
850describe('timeUntilStale', () => {
851 it('should return a number', () => {
852 expectTypeOf(timeUntilStale).returns.toEqualTypeOf<number>()
853 })
854​
855 it('should accept the staleTime argument optionally', () => {
856 expectTypeOf(timeUntilStale).parameters.toEqualTypeOf<
857 [updatedAt: number, staleTime?: number]
858 >()
859​
860 expectTypeOf(timeUntilStale(1)).toEqualTypeOf<number>()
861 expectTypeOf(timeUntilStale(1, 2)).toEqualTypeOf<number>()
862 })
863})
864​
865describe('replaceData', () => {
866 it('should return TData rather than the options type', () => {
867 expectTypeOf(
868 replaceData<{ value: string }, QueryOptions<any, any, any, any>>,
869 ).returns.toEqualTypeOf<{ value: string }>()
870 })
871​
872 it('should widen only the previous data with undefined', () => {
873 type Params = Parameters<
874 typeof replaceData<{ value: string }, QueryOptions<any, any, any, any>>
875 >
876​
877 expectTypeOf<Params[0]>().toEqualTypeOf<{ value: string } | undefined>()
878 expectTypeOf<Params[1]>().toEqualTypeOf<{ value: string }>()
879 })
880​
881 it('should constrain TOptions to QueryOptions', () => {
882 expectTypeOf(
883 replaceData<{ value: string }, QueryOptions<any, any, any, any>>,
884 )
885 .parameter(2)
886 .toEqualTypeOf<QueryOptions<any, any, any, any>>()
887​
888 // @ts-expect-error a primitive does not satisfy the QueryOptions constraint
889 replaceData<{ value: string }, number>({ value: 'a' }, { value: 'b' }, 1)
890 })
891})