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

utils.test.tsx

751 lines24.4 KB

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