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

utils.test.tsx

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