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