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

utils.test.tsx

814 lines26.7 KB

1import { createKey } from '@tanstack/query-test-utils'
2import { describe, expect, it, vi } from 'vitest'
3import { QueryClient } from '..'
4import { Mutation } from '../mutation'
5import {
6 addConsumeAwareSignal,
7 addToArray,
8 ensureQueryFn,
9 hashKey,
10 hashQueryKeyByOptions,
11 isPlainArray,
12 isPlainObject,
13 isValidTimeout,
14 keepPreviousData,
15 matchMutation,
16 partialMatchKey,
17 replaceEqualDeep,
18 shallowEqualObjects,
19 shouldThrowError,
20 skipToken,
21} from '../utils'
22import type { QueryFunctionContext } from '..'
23​
24describe('core/utils', () => {
25 describe('hashQueryKeyByOptions', () => {
26 it('should use custom hash function when provided in options', () => {
27 const key = ['test', { a: 1, b: 2 }]
28 const customHashFn = vi.fn<() => string>(() => 'custom-hash')
29​
30 const result = hashQueryKeyByOptions(key, {
31 queryKeyHashFn: customHashFn,
32 })
33​
34 expect(customHashFn).toHaveBeenCalledWith(key)
35 expect(result).toBe('custom-hash')
36 })
37​
38 it('should use default hash function when no options provided', () => {
39 const key = ['test', { a: 1, b: 2 }]
40 const defaultResult = hashKey(key)
41 const result = hashQueryKeyByOptions(key)
42​
43 expect(result).toStrictEqual(defaultResult)
44 })
45 })
46​
47 describe('shallowEqualObjects', () => {
48 it('should return `true` for shallow equal objects', () => {
49 expect(shallowEqualObjects({ a: 1 }, { a: 1 })).toBe(true)
50 })
51​
52 it('should return `true` when comparing an object with inherited properties to itself', () => {
53 const a = { a: 1 }
54 Object.setPrototypeOf(a, { inherited: 1 })
55​
56 expect(shallowEqualObjects(a, a)).toBe(true)
57 })
58​
59 it('should ignore inherited properties when comparing equal own properties', () => {
60 const a = { a: 1 }
61 const b = { a: 1 }
62 Object.setPrototypeOf(a, { inherited: 1 })
63​
64 expect(shallowEqualObjects(a, b)).toBe(true)
65 expect(shallowEqualObjects(b, a)).toBe(true)
66​
67 Object.setPrototypeOf(b, { inherited: 2 })
68​
69 expect(shallowEqualObjects(a, b)).toBe(true)
70 expect(shallowEqualObjects(b, a)).toBe(true)
71 })
72​
73 it('should return `false` for non shallow equal objects', () => {
74 expect(shallowEqualObjects({ a: 1 }, { a: 2 })).toBe(false)
75 })
76​
77 it('should return `false` if lengths are not equal', () => {
78 expect(shallowEqualObjects({ a: 1 }, { a: 1, b: 2 })).toBe(false)
79 })
80​
81 it('should return false if b is undefined', () => {
82 expect(shallowEqualObjects({ a: 1 }, undefined)).toBe(false)
83 })
84​
85 it('should return `false` for same-length objects with different keys', () => {
86 expect(
87 shallowEqualObjects({ a: 1, b: undefined }, { a: 1, c: undefined }),
88 ).toBe(false)
89 expect(shallowEqualObjects({ a: 1, b: 2 }, { a: 1, c: 2 })).toBe(false)
90 })
91 })
92​
93 describe('isPlainObject', () => {
94 it('should return `true` for a plain object', () => {
95 expect(isPlainObject({})).toBe(true)
96 })
97​
98 it('should return `true` for a plain object with an own null constructor property', () => {
99 expect(isPlainObject(JSON.parse('{"constructor":null}'))).toBe(true)
100 })
101​
102 it('should return `false` for an array', () => {
103 expect(isPlainObject([])).toBe(false)
104 })
105​
106 it('should return `false` for null', () => {
107 expect(isPlainObject(null)).toBe(false)
108 })
109​
110 it('should return `false` for undefined', () => {
111 expect(isPlainObject(undefined)).toBe(false)
112 })
113​
114 it('should return `true` for object with an undefined constructor', () => {
115 expect(isPlainObject(Object.create(null))).toBe(true)
116 })
117​
118 it('should return `false` if constructor does not have an Object-specific method', () => {
119 class Foo {
120 abc: any
121 constructor() {
122 this.abc = {}
123 }
124 }
125 expect(isPlainObject(new Foo())).toBe(false)
126 })
127​
128 it('should return `false` if the object has a modified prototype', () => {
129 function Graph(this: any) {
130 this.vertices = []
131 this.edges = []
132 }
133​
134 Graph.prototype.addVertex = function (v: any) {
135 this.vertices.push(v)
136 }
137​
138 expect(isPlainObject(Object.create(Graph))).toBe(false)
139 })
140​
141 it('should return `false` for object with custom prototype', () => {
142 const CustomProto = Object.create({ a: 1 })
143 const obj = Object.create(CustomProto)
144 obj.b = 2
145​
146 expect(isPlainObject(obj)).toBe(false)
147 })
148 })
149​
150 describe('isPlainArray', () => {
151 it('should return `true` for plain arrays', () => {
152 expect(isPlainArray([1, 2])).toBe(true)
153 })
154​
155 it('should return `false` for non plain arrays', () => {
156 expect(isPlainArray(Object.assign([1, 2], { a: 'b' }))).toBe(false)
157 })
158 })
159​
160 describe('partialMatchKey', () => {
161 it('should return `true` if a includes b', () => {
162 const a = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }]
163 const b = [{ a: { b: 'b' }, c: 'c', d: [] }]
164 expect(partialMatchKey(a, b)).toBe(true)
165 })
166​
167 it('should return `false` if a does not include b', () => {
168 const a = [{ a: { b: 'b' }, c: 'c', d: [] }]
169 const b = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }]
170 expect(partialMatchKey(a, b)).toBe(false)
171 })
172​
173 it('should return `true` if array a includes array b', () => {
174 const a = [1, 2, 3]
175 const b = [1, 2]
176 expect(partialMatchKey(a, b)).toBe(true)
177 })
178​
179 it('should return `false` if a is shorter and b has a trailing undefined', () => {
180 const a = [1]
181 const b = [1, undefined]
182 expect(partialMatchKey(a, b)).toBe(false)
183 })
184​
185 it('should return `false` if a is null and b is not', () => {
186 const a = [null]
187 const b = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }]
188 expect(partialMatchKey(a, b)).toBe(false)
189 })
190​
191 it('should return `false` if a contains null and b is not', () => {
192 const a = [{ a: null, c: 'c', d: [] }]
193 const b = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }]
194 expect(partialMatchKey(a, b)).toBe(false)
195 })
196​
197 it('should return `false` if b is null and a is not', () => {
198 const a = [{ a: { b: 'b' }, c: 'c', d: [] }]
199 const b = [null]
200 expect(partialMatchKey(a, b)).toBe(false)
201 })
202​
203 it('should return `false` if b contains null and a is not', () => {
204 const a = [{ a: { b: 'b' }, c: 'c', d: [] }]
205 const b = [{ a: null, c: 'c', d: [{ d: 'd ' }] }]
206 expect(partialMatchKey(a, b)).toBe(false)
207 })
208​
209 it('should treat undefined object properties as matching missing properties', () => {
210 const queryKeyWithUndefined = ['todos', { filters: undefined }]
211 const queryKeyWithoutProperty = ['todos', {}]
212​
213 expect(
214 partialMatchKey(queryKeyWithoutProperty, queryKeyWithUndefined),
215 ).toBe(true)
216 expect(
217 partialMatchKey(queryKeyWithUndefined, queryKeyWithoutProperty),
218 ).toBe(true)
219 })
220​
221 it('should not match an array element against an empty object', () => {
222 expect(partialMatchKey(['todos', ['a']], ['todos', {}])).toBe(false)
223 })
224​
225 it('should not match an object with numeric keys against an array element', () => {
226 expect(partialMatchKey(['todos', { 0: 'a' }], ['todos', ['a']])).toBe(
227 false,
228 )
229 })
230 })
231​
232 describe('replaceEqualDeep', () => {
233 it('should return the previous value when the next value is an equal primitive', () => {
234 expect(replaceEqualDeep(1, 1)).toBe(1)
235 expect(replaceEqualDeep('1', '1')).toBe('1')
236 expect(replaceEqualDeep(true, true)).toBe(true)
237 expect(replaceEqualDeep(false, false)).toBe(false)
238 expect(replaceEqualDeep(null, null)).toBeNull()
239 expect(replaceEqualDeep(undefined, undefined)).toBeUndefined()
240 })
241​
242 it('should return the next value when the previous value is a different value', () => {
243 const date1 = new Date()
244 const date2 = new Date()
245​
246 expect(replaceEqualDeep(1, 0)).toBe(0)
247 expect(replaceEqualDeep(1, 2)).toBe(2)
248 expect(replaceEqualDeep('1', '2')).toBe('2')
249 expect(replaceEqualDeep(true, false)).toBe(false)
250 expect(replaceEqualDeep(false, true)).toBe(true)
251 expect(replaceEqualDeep(date1, date2)).toBe(date2)
252 })
253​
254 it('should return the next value when the previous value is a different type', () => {
255 const array = [1]
256 const object = { a: 'a' }
257 expect(replaceEqualDeep(0, undefined)).toBeUndefined()
258 expect(replaceEqualDeep(undefined, 0)).toBe(0)
259 expect(replaceEqualDeep(2, undefined)).toBeUndefined()
260 expect(replaceEqualDeep(undefined, 2)).toBe(2)
261 expect(replaceEqualDeep(undefined, null)).toBeNull()
262 expect(replaceEqualDeep(null, undefined)).toBeUndefined()
263 expect(replaceEqualDeep({}, undefined)).toBeUndefined()
264 expect(replaceEqualDeep([], undefined)).toBeUndefined()
265 expect(replaceEqualDeep(array, object)).toBe(object)
266 expect(replaceEqualDeep(object, array)).toBe(array)
267 })
268​
269 it('should return the previous value when the next value is an equal array', () => {
270 const prev = [1, 2]
271 const next = [1, 2]
272 expect(replaceEqualDeep(prev, next)).toBe(prev)
273 })
274​
275 it('should return a copy when the previous value is a different array subset', () => {
276 const prev = [1, 2]
277 const next = [1, 2, 3]
278 const result = replaceEqualDeep(prev, next)
279 expect(result).toStrictEqual(next)
280 expect(result).not.toBe(prev)
281 expect(result).not.toBe(next)
282 })
283​
284 it('should return a copy when the previous value is a different array superset', () => {
285 const prev = [1, 2, 3]
286 const next = [1, 2]
287 const result = replaceEqualDeep(prev, next)
288 expect(result).toStrictEqual(next)
289 expect(result).not.toBe(prev)
290 expect(result).not.toBe(next)
291 })
292​
293 it('should return the previous value when the next value is an equal empty array', () => {
294 const prev: Array<any> = []
295 const next: Array<any> = []
296 expect(replaceEqualDeep(prev, next)).toBe(prev)
297 })
298​
299 it('should return the previous value when the next value is an equal empty object', () => {
300 const prev = {}
301 const next = {}
302 expect(replaceEqualDeep(prev, next)).toBe(prev)
303 })
304​
305 it('should return the previous value when the next value is an equal object', () => {
306 const prev = { a: 'a' }
307 const next = { a: 'a' }
308 expect(replaceEqualDeep(prev, next)).toBe(prev)
309 })
310​
311 it('should replace different values in objects', () => {
312 const prev = { a: { b: 'b' }, c: 'c' }
313 const next = { a: { b: 'b' }, c: 'd' }
314 const result = replaceEqualDeep(prev, next)
315 expect(result).toStrictEqual(next)
316 expect(result).not.toBe(prev)
317 expect(result).not.toBe(next)
318 expect(result.a).toBe(prev.a)
319 expect(result.c).toBe(next.c)
320 })
321​
322 it('should replace different values in arrays', () => {
323 const prev = [1, { a: 'a' }, { b: { b: 'b' } }, [1]] as const
324 const next = [1, { a: 'a' }, { b: { b: 'c' } }, [1]] as const
325 const result = replaceEqualDeep(prev, next)
326 expect(result).toStrictEqual(next)
327 expect(result).not.toBe(prev)
328 expect(result).not.toBe(next)
329 expect(result[0]).toBe(prev[0])
330 expect(result[1]).toBe(prev[1])
331 expect(result[2]).not.toBe(next[2])
332 expect(result[2].b.b).toBe(next[2].b.b)
333 expect(result[3]).toBe(prev[3])
334 })
335​
336 it('should replace different values in arrays when the next value is a subset', () => {
337 const prev = [{ a: 'a' }, { b: 'b' }, { c: 'c' }]
338 const next = [{ a: 'a' }, { b: 'b' }]
339 const result = replaceEqualDeep(prev, next)
340 expect(result).toStrictEqual(next)
341 expect(result).not.toBe(prev)
342 expect(result).not.toBe(next)
343 expect(result[0]).toBe(prev[0])
344 expect(result[1]).toBe(prev[1])
345 expect(result[2]).toBeUndefined()
346 })
347​
348 it('should replace different values in arrays when the next value is a superset', () => {
349 const prev = [{ a: 'a' }, { b: 'b' }]
350 const next = [{ a: 'a' }, { b: 'b' }, { c: 'c' }]
351 const result = replaceEqualDeep(prev, next)
352 expect(result).toStrictEqual(next)
353 expect(result).not.toBe(prev)
354 expect(result).not.toBe(next)
355 expect(result[0]).toBe(prev[0])
356 expect(result[1]).toBe(prev[1])
357 expect(result[2]).toBe(next[2])
358 })
359​
360 it('should copy objects which are not arrays or objects', () => {
361 const prev = [{ a: 'a' }, { b: 'b' }, { c: 'c' }, 1]
362 const next = [{ a: 'a' }, new Map(), { c: 'c' }, 2]
363 const result = replaceEqualDeep(prev, next)
364 expect(result).not.toBe(prev)
365 expect(result).not.toBe(next)
366 expect(result[0]).toBe(prev[0])
367 expect(result[1]).toBe(next[1])
368 expect(result[2]).toBe(prev[2])
369 expect(result[3]).toBe(next[3])
370 })
371​
372 it('should support equal objects which are not arrays or objects', () => {
373 const map = new Map()
374 const prev = [map, [1]]
375 const next = [map, [1]]
376 const result = replaceEqualDeep(prev, next)
377 expect(result).toBe(prev)
378 })
379​
380 it('should support non equal objects which are not arrays or objects', () => {
381 const map1 = new Map()
382 const map2 = new Map()
383 const prev = [map1, [1]]
384 const next = [map2, [1]]
385 const result = replaceEqualDeep(prev, next)
386 expect(result).not.toBe(prev)
387 expect(result).not.toBe(next)
388 expect(result[0]).toBe(next[0])
389 expect(result[1]).toBe(prev[1])
390 })
391​
392 it('should support objects which are not plain arrays', () => {
393 const prev = Object.assign([1, 2], { a: { b: 'b' }, c: 'c' })
394 const next = Object.assign([1, 2], { a: { b: 'b' }, c: 'c' })
395 const result = replaceEqualDeep(prev, next)
396 expect(result).toBe(next)
397 })
398​
399 it('should replace all parent objects if some nested value changes', () => {
400 const prev = {
401 todo: { id: '1', meta: { createdAt: 0 }, state: { done: false } },
402 otherTodo: { id: '2', meta: { createdAt: 0 }, state: { done: true } },
403 }
404 const next = {
405 todo: { id: '1', meta: { createdAt: 0 }, state: { done: true } },
406 otherTodo: { id: '2', meta: { createdAt: 0 }, state: { done: true } },
407 }
408 const result = replaceEqualDeep(prev, next)
409 expect(result).toStrictEqual(next)
410 expect(result).not.toBe(prev)
411 expect(result).not.toBe(next)
412 expect(result.todo).not.toBe(prev.todo)
413 expect(result.todo).not.toBe(next.todo)
414 expect(result.todo.id).toBe(next.todo.id)
415 expect(result.todo.meta).toBe(prev.todo.meta)
416 expect(result.todo.state).not.toBe(next.todo.state)
417 expect(result.todo.state.done).toBe(next.todo.state.done)
418 expect(result.otherTodo).toBe(prev.otherTodo)
419 })
420​
421 it('should replace all parent arrays if some nested value changes', () => {
422 const prev = {
423 todos: [
424 { id: '1', meta: { createdAt: 0 }, state: { done: false } },
425 { id: '2', meta: { createdAt: 0 }, state: { done: true } },
426 ],
427 }
428 const next = {
429 todos: [
430 { id: '1', meta: { createdAt: 0 }, state: { done: true } },
431 { id: '2', meta: { createdAt: 0 }, state: { done: true } },
432 ],
433 }
434 const result = replaceEqualDeep(prev, next)
435 expect(result).toStrictEqual(next)
436 expect(result).not.toBe(prev)
437 expect(result).not.toBe(next)
438 expect(result.todos).not.toBe(prev.todos)
439 expect(result.todos).not.toBe(next.todos)
440 expect(result.todos[0]).not.toBe(prev.todos[0])
441 expect(result.todos[0]).not.toBe(next.todos[0])
442 expect(result.todos[0]?.id).toBe(next.todos[0]?.id)
443 expect(result.todos[0]?.meta).toBe(prev.todos[0]?.meta)
444 expect(result.todos[0]?.state).not.toBe(next.todos[0]?.state)
445 expect(result.todos[0]?.state.done).toBe(next.todos[0]?.state.done)
446 expect(result.todos[1]).toBe(prev.todos[1])
447 })
448​
449 it('should correctly handle objects with the same number of properties and one property being undefined', () => {
450 const obj1 = { a: 2, c: 123 }
451 const obj2 = { a: 2, b: undefined }
452 const result = replaceEqualDeep(obj1, obj2)
453 expect(result).toStrictEqual(obj2)
454 })
455​
456 it('should be able to share values that contain undefined', () => {
457 const current = [
458 {
459 data: undefined,
460 foo: true,
461 },
462 ]
463​
464 const next = replaceEqualDeep(current, [
465 {
466 data: undefined,
467 foo: true,
468 },
469 ])
470​
471 expect(current).toBe(next)
472 })
473​
474 it('should return the previous value when both values are an array of undefined', () => {
475 const current = [undefined]
476 const next = replaceEqualDeep(current, [undefined])
477​
478 expect(next).toBe(current)
479 })
480​
481 it('should return the previous value when both values are an array that contains undefined', () => {
482 const current = [{ foo: 1 }, undefined]
483 const next = replaceEqualDeep(current, [{ foo: 1 }, undefined])
484​
485 expect(next).toBe(current)
486 })
487​
488 it('should stop structural sharing once the recursion depth exceeds the limit', () => {
489 const nest = (depth: number, leaf: number) => {
490 let value: any = { leaf }
491 for (let i = 0; i < depth; i++) {
492 value = { child: value }
493 }
494 return value
495 }
496​
497 const prev = nest(502, 1)
498 const next = nest(502, 2)
499 const result = replaceEqualDeep(prev, next)
500​
501 let resultNode = result
502 let nextNode = next
503 for (let i = 0; i < 502; i++) {
504 resultNode = resultNode.child
505 nextNode = nextNode.child
506 }
507​
508 expect(resultNode).toBe(nextNode)
509 })
510 })
511​
512 describe('matchMutation', () => {
513 it('should return false if mutationKey options is undefined', () => {
514 const filters = { mutationKey: createKey() }
515 const queryClient = new QueryClient()
516 const mutation = new Mutation({
517 client: queryClient,
518 mutationId: 1,
519 mutationCache: queryClient.getMutationCache(),
520 options: {},
521 })
522​
523 expect(matchMutation(filters, mutation)).toBe(false)
524 })
525 })
526​
527 describe('keepPreviousData', () => {
528 it('should return the parameter as is', () => {
529 const x = { a: 1, b: 2 }
530 expect(keepPreviousData(x)).toBe(x)
531 })
532 })
533​
534 describe('addToArray (append)', () => {
535 it('should add item to the end of the array', () => {
536 const items = [1, 2, 3]
537 const newItems = addToArray(items, 4)
538 expect(newItems).toStrictEqual([1, 2, 3, 4])
539 })
540​
541 it('should not exceed max if provided', () => {
542 const items = [1, 2, 3]
543 const newItems = addToArray(items, 4, 3)
544 expect(newItems).toStrictEqual([2, 3, 4])
545 })
546​
547 it('should not exceed max when items already exceed max', () => {
548 const items = [1, 2, 3, 4, 5]
549 const newItems = addToArray(items, 6, 3)
550 expect(newItems).toStrictEqual([4, 5, 6])
551 })
552​
553 it('should add item to the end of the array when max = 0', () => {
554 const items = [1, 2, 3]
555 const item = 4
556 const max = 0
557 expect(addToArray(items, item, max)).toStrictEqual([1, 2, 3, 4])
558 })
559​
560 it('should add item to the end of the array when max is undefined', () => {
561 const items = [1, 2, 3]
562 const item = 4
563 const max = undefined
564 expect(addToArray(items, item, max)).toStrictEqual([1, 2, 3, 4])
565 })
566 })
567​
568 describe('addToArray (prepend)', () => {
569 it('should add an item to the start of the array', () => {
570 const items = [1, 2, 3]
571 const item = 4
572 const newItems = addToArray(items, item, undefined, true)
573 expect(newItems).toStrictEqual([4, 1, 2, 3])
574 })
575​
576 it('should respect the max argument', () => {
577 const items = [1, 2, 3]
578 const item = 4
579 const max = 2
580 const newItems = addToArray(items, item, max, true)
581 expect(newItems).toStrictEqual([4, 1])
582 })
583​
584 it('should not exceed max when items already exceed max', () => {
585 const items = [1, 2, 3, 4, 5]
586 const newItems = addToArray(items, 6, 3, true)
587 expect(newItems).toStrictEqual([6, 1, 2])
588 })
589​
590 it('should not remove any items if max = 0', () => {
591 const items = [1, 2, 3]
592 const item = 4
593 const max = 0
594 const newItems = addToArray(items, item, max, true)
595 expect(newItems).toStrictEqual([4, 1, 2, 3])
596 })
597​
598 it('should not remove any items if max is undefined', () => {
599 const items = [1, 2, 3]
600 const item = 4
601 const max = undefined
602 const newItems = addToArray(items, item, max, true)
603 expect(newItems).toStrictEqual([4, 1, 2, 3])
604 })
605 })
606​
607 describe('hashKey', () => {
608 it('should hash primitives correctly', () => {
609 expect(hashKey(['test'])).toStrictEqual(JSON.stringify(['test']))
610 expect(hashKey([123])).toStrictEqual(JSON.stringify([123]))
611 expect(hashKey([null])).toStrictEqual(JSON.stringify([null]))
612 })
613​
614 it('should hash objects with sorted keys consistently', () => {
615 const key1 = [{ b: 2, a: 1 }]
616 const key2 = [{ a: 1, b: 2 }]
617​
618 const hash1 = hashKey(key1)
619 const hash2 = hashKey(key2)
620​
621 expect(hash1).toStrictEqual(hash2)
622 expect(hash1).toStrictEqual(JSON.stringify([{ a: 1, b: 2 }]))
623 })
624​
625 it('should hash arrays consistently', () => {
626 const arr1 = [{ b: 2, a: 1 }, 'test', 123]
627 const arr2 = [{ a: 1, b: 2 }, 'test', 123]
628​
629 expect(hashKey(arr1)).toStrictEqual(hashKey(arr2))
630 })
631​
632 it('should handle nested objects with sorted keys', () => {
633 const nested1 = [{ a: { d: 4, c: 3 }, b: 2 }]
634 const nested2 = [{ b: 2, a: { c: 3, d: 4 } }]
635​
636 expect(hashKey(nested1)).toStrictEqual(hashKey(nested2))
637 })
638​
639 it('should hash undefined object properties the same as missing properties', () => {
640 const withUndefined = ['todos', { filters: undefined }]
641 const withoutProperty = ['todos', {}]
642​
643 expect(hashKey(withUndefined)).toStrictEqual(hashKey(withoutProperty))
644 })
645 })
646​
647 describe('isValidTimeout', () => {
648 it('should accept valid timeout values', () => {
649 expect(isValidTimeout(0)).toBe(true)
650 expect(isValidTimeout(1000)).toBe(true)
651 })
652​
653 it('should reject a negative timeout value', () => {
654 expect(isValidTimeout(-1)).toBe(false)
655 })
656​
657 it('should reject NaN', () => {
658 expect(isValidTimeout(Number.NaN)).toBe(false)
659 })
660​
661 it('should reject Infinity', () => {
662 expect(isValidTimeout(Number.POSITIVE_INFINITY)).toBe(false)
663 })
664​
665 it('should reject a string timeout value', () => {
666 expect(isValidTimeout('1000')).toBe(false)
667 })
668​
669 it('should reject undefined', () => {
670 expect(isValidTimeout(undefined)).toBe(false)
671 })
672 })
673​
674 describe('ensureQueryFn', () => {
675 const context = {} as QueryFunctionContext
676​
677 it('should return a function that resolves to initialPromise when queryFn is missing and initialPromise is provided', async () => {
678 const initialPromise = Promise.resolve('initial-data')
679​
680 const resolved = ensureQueryFn(
681 { queryHash: '["key"]' },
682 { initialPromise },
683 )
684​
685 await expect(resolved(context)).resolves.toBe('initial-data')
686 })
687​
688 it('should return a function that rejects when initialPromise rejects', async () => {
689 const error = new Error('initial-promise-error')
690 const initialPromise = Promise.reject(error)
691​
692 const resolved = ensureQueryFn(
693 { queryHash: '["key"]' },
694 { initialPromise },
695 )
696​
697 await expect(resolved(context)).rejects.toBe(error)
698 })
699​
700 it('should return a function that rejects with missing queryFn error when queryFn is set to skipToken', async () => {
701 const consoleErrorMock = vi
702 .spyOn(console, 'error')
703 .mockReturnValue(undefined)
704​
705 const resolved = ensureQueryFn({
706 queryFn: skipToken,
707 queryHash: '["skip"]',
708 })
709​
710 expect(consoleErrorMock).toHaveBeenCalledWith(
711 expect.stringContaining(
712 'Attempted to invoke queryFn when set to skipToken',
713 ),
714 )
715 await expect(resolved(context)).rejects.toThrow(
716 'Missing queryFn: \'["skip"]\'',
717 )
718 })
719 })
720​
721 describe('shouldThrowError', () => {
722 it('should return the result of executing throwOnError if throwOnError parameter is a function', () => {
723 const throwOnError = (error: Error) => error.message === 'test error'
724 expect(shouldThrowError(throwOnError, [new Error('test error')])).toBe(
725 true,
726 )
727 expect(shouldThrowError(throwOnError, [new Error('other error')])).toBe(
728 false,
729 )
730 })
731​
732 it('should return throwOnError parameter itself if throwOnError is not a function', () => {
733 expect(shouldThrowError(true, [new Error('test error')])).toBe(true)
734 expect(shouldThrowError(false, [new Error('test error')])).toBe(false)
735 expect(shouldThrowError(undefined, [new Error('test error')])).toBe(false)
736 })
737 })
738​
739 describe('addConsumeAwareSignal', () => {
740 it('should allow page parameters to be passed to URLSearchParams', () => {
741 const controller = new AbortController()
742 const context = addConsumeAwareSignal(
743 { pageParam: 'cursor' },
744 () => controller.signal,
745 vi.fn(),
746 controller.signal,
747 )
748 const { signal, ...params } = context
749​
750 expect(signal).toBe(controller.signal)
751 expect(new URLSearchParams(params).toString()).toBe('pageParam=cursor')
752 })
753​
754 it('should expose the signal on the query context while preserving its properties', () => {
755 const controller = new AbortController()
756 const key = createKey()
757 const context = addConsumeAwareSignal(
758 { queryKey: key, meta: undefined },
759 () => controller.signal,
760 vi.fn(),
761 )
762​
763 expect(context.queryKey).toBe(key)
764 expect(context.signal).toBe(controller.signal)
765 })
766​
767 it('should call onCancelled immediately when the signal is already aborted on first access', () => {
768 const controller = new AbortController()
769 controller.abort()
770 const onCancelled = vi.fn<() => void>()
771 const object = addConsumeAwareSignal(
772 {},
773 () => controller.signal,
774 onCancelled,
775 )
776​
777 // Access the signal to consume it
778 void object.signal
779​
780 expect(onCancelled).toHaveBeenCalledTimes(1)
781 })
782​
783 it('should flag cancellation when the consumed signal aborts, mirroring streamed/infinite queries', () => {
784 const controller = new AbortController()
785 let cancelled = false
786 const context = addConsumeAwareSignal(
787 { queryKey: createKey() },
788 () => controller.signal,
789 () => (cancelled = true),
790 )
791​
792 void context.signal
793 expect(cancelled).toBe(false)
794​
795 controller.abort()
796 expect(cancelled).toBe(true)
797 })
798​
799 it('should consume the signal only once across repeated accesses', () => {
800 const controller = new AbortController()
801 const addEventListener = vi.spyOn(controller.signal, 'addEventListener')
802 const context = addConsumeAwareSignal(
803 { queryKey: createKey() },
804 () => controller.signal,
805 vi.fn(),
806 )
807​
808 expect(context.signal).toBe(controller.signal)
809 expect(context.signal).toBe(controller.signal)
810​
811 expect(addEventListener).toHaveBeenCalledTimes(1)
812 })
813 })
814})