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