import { createKey } from '@tanstack/query-test-utils' import { describe, expect, it, vi } from 'vitest' import { QueryClient } from '..' import { Mutation } from '../mutation' import { addConsumeAwareSignal, addToArray, ensureQueryFn, hashKey, hashQueryKeyByOptions, isPlainArray, isPlainObject, isValidTimeout, keepPreviousData, matchMutation, partialMatchKey, replaceEqualDeep, shallowEqualObjects, shouldThrowError, skipToken, } from '../utils' import type { QueryFunctionContext } from '..' describe('core/utils', () => { describe('hashQueryKeyByOptions', () => { it('should use custom hash function when provided in options', () => { const key = ['test', { a: 1, b: 2 }] const customHashFn = vi.fn<() => string>(() => 'custom-hash') const result = hashQueryKeyByOptions(key, { queryKeyHashFn: customHashFn, }) expect(customHashFn).toHaveBeenCalledWith(key) expect(result).toBe('custom-hash') }) it('should use default hash function when no options provided', () => { const key = ['test', { a: 1, b: 2 }] const defaultResult = hashKey(key) const result = hashQueryKeyByOptions(key) expect(result).toStrictEqual(defaultResult) }) }) describe('shallowEqualObjects', () => { it('should return `true` for shallow equal objects', () => { expect(shallowEqualObjects({ a: 1 }, { a: 1 })).toBe(true) }) it('should return `true` when comparing an object with inherited properties to itself', () => { const a = { a: 1 } Object.setPrototypeOf(a, { inherited: 1 }) expect(shallowEqualObjects(a, a)).toBe(true) }) it('should ignore inherited properties when comparing equal own properties', () => { const a = { a: 1 } const b = { a: 1 } Object.setPrototypeOf(a, { inherited: 1 }) expect(shallowEqualObjects(a, b)).toBe(true) expect(shallowEqualObjects(b, a)).toBe(true) Object.setPrototypeOf(b, { inherited: 2 }) expect(shallowEqualObjects(a, b)).toBe(true) expect(shallowEqualObjects(b, a)).toBe(true) }) it('should return `false` for non shallow equal objects', () => { expect(shallowEqualObjects({ a: 1 }, { a: 2 })).toBe(false) }) it('should return `false` if lengths are not equal', () => { expect(shallowEqualObjects({ a: 1 }, { a: 1, b: 2 })).toBe(false) }) it('should return false if b is undefined', () => { expect(shallowEqualObjects({ a: 1 }, undefined)).toBe(false) }) it('should return `false` for same-length objects with different keys', () => { expect( shallowEqualObjects({ a: 1, b: undefined }, { a: 1, c: undefined }), ).toBe(false) expect(shallowEqualObjects({ a: 1, b: 2 }, { a: 1, c: 2 })).toBe(false) }) }) describe('isPlainObject', () => { it('should return `true` for a plain object', () => { expect(isPlainObject({})).toBe(true) }) it('should return `true` for a plain object with an own null constructor property', () => { expect(isPlainObject(JSON.parse('{"constructor":null}'))).toBe(true) }) it('should return `false` for an array', () => { expect(isPlainObject([])).toBe(false) }) it('should return `false` for null', () => { expect(isPlainObject(null)).toBe(false) }) it('should return `false` for undefined', () => { expect(isPlainObject(undefined)).toBe(false) }) it('should return `true` for object with an undefined constructor', () => { expect(isPlainObject(Object.create(null))).toBe(true) }) it('should return `false` if constructor does not have an Object-specific method', () => { class Foo { abc: any constructor() { this.abc = {} } } expect(isPlainObject(new Foo())).toBe(false) }) it('should return `false` if the object has a modified prototype', () => { function Graph(this: any) { this.vertices = [] this.edges = [] } Graph.prototype.addVertex = function (v: any) { this.vertices.push(v) } expect(isPlainObject(Object.create(Graph))).toBe(false) }) it('should return `false` for object with custom prototype', () => { const CustomProto = Object.create({ a: 1 }) const obj = Object.create(CustomProto) obj.b = 2 expect(isPlainObject(obj)).toBe(false) }) }) describe('isPlainArray', () => { it('should return `true` for plain arrays', () => { expect(isPlainArray([1, 2])).toBe(true) }) it('should return `false` for non plain arrays', () => { expect(isPlainArray(Object.assign([1, 2], { a: 'b' }))).toBe(false) }) }) describe('partialMatchKey', () => { it('should return `true` if a includes b', () => { const a = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }] const b = [{ a: { b: 'b' }, c: 'c', d: [] }] expect(partialMatchKey(a, b)).toBe(true) }) it('should return `false` if a does not include b', () => { const a = [{ a: { b: 'b' }, c: 'c', d: [] }] const b = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }] expect(partialMatchKey(a, b)).toBe(false) }) it('should return `true` if array a includes array b', () => { const a = [1, 2, 3] const b = [1, 2] expect(partialMatchKey(a, b)).toBe(true) }) it('should return `false` if a is shorter and b has a trailing undefined', () => { const a = [1] const b = [1, undefined] expect(partialMatchKey(a, b)).toBe(false) }) it('should return `false` if a is null and b is not', () => { const a = [null] const b = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }] expect(partialMatchKey(a, b)).toBe(false) }) it('should return `false` if a contains null and b is not', () => { const a = [{ a: null, c: 'c', d: [] }] const b = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }] expect(partialMatchKey(a, b)).toBe(false) }) it('should return `false` if b is null and a is not', () => { const a = [{ a: { b: 'b' }, c: 'c', d: [] }] const b = [null] expect(partialMatchKey(a, b)).toBe(false) }) it('should return `false` if b contains null and a is not', () => { const a = [{ a: { b: 'b' }, c: 'c', d: [] }] const b = [{ a: null, c: 'c', d: [{ d: 'd ' }] }] expect(partialMatchKey(a, b)).toBe(false) }) it('should treat undefined object properties as matching missing properties', () => { const queryKeyWithUndefined = ['todos', { filters: undefined }] const queryKeyWithoutProperty = ['todos', {}] expect( partialMatchKey(queryKeyWithoutProperty, queryKeyWithUndefined), ).toBe(true) expect( partialMatchKey(queryKeyWithUndefined, queryKeyWithoutProperty), ).toBe(true) }) it('should not match an array element against an empty object', () => { expect(partialMatchKey(['todos', ['a']], ['todos', {}])).toBe(false) }) it('should not match an object with numeric keys against an array element', () => { expect(partialMatchKey(['todos', { 0: 'a' }], ['todos', ['a']])).toBe( false, ) }) }) describe('replaceEqualDeep', () => { it('should return the previous value when the next value is an equal primitive', () => { expect(replaceEqualDeep(1, 1)).toBe(1) expect(replaceEqualDeep('1', '1')).toBe('1') expect(replaceEqualDeep(true, true)).toBe(true) expect(replaceEqualDeep(false, false)).toBe(false) expect(replaceEqualDeep(null, null)).toBeNull() expect(replaceEqualDeep(undefined, undefined)).toBeUndefined() }) it('should return the next value when the previous value is a different value', () => { const date1 = new Date() const date2 = new Date() expect(replaceEqualDeep(1, 0)).toBe(0) expect(replaceEqualDeep(1, 2)).toBe(2) expect(replaceEqualDeep('1', '2')).toBe('2') expect(replaceEqualDeep(true, false)).toBe(false) expect(replaceEqualDeep(false, true)).toBe(true) expect(replaceEqualDeep(date1, date2)).toBe(date2) }) it('should return the next value when the previous value is a different type', () => { const array = [1] const object = { a: 'a' } expect(replaceEqualDeep(0, undefined)).toBeUndefined() expect(replaceEqualDeep(undefined, 0)).toBe(0) expect(replaceEqualDeep(2, undefined)).toBeUndefined() expect(replaceEqualDeep(undefined, 2)).toBe(2) expect(replaceEqualDeep(undefined, null)).toBeNull() expect(replaceEqualDeep(null, undefined)).toBeUndefined() expect(replaceEqualDeep({}, undefined)).toBeUndefined() expect(replaceEqualDeep([], undefined)).toBeUndefined() expect(replaceEqualDeep(array, object)).toBe(object) expect(replaceEqualDeep(object, array)).toBe(array) }) it('should return the previous value when the next value is an equal array', () => { const prev = [1, 2] const next = [1, 2] expect(replaceEqualDeep(prev, next)).toBe(prev) }) it('should return a copy when the previous value is a different array subset', () => { const prev = [1, 2] const next = [1, 2, 3] const result = replaceEqualDeep(prev, next) expect(result).toStrictEqual(next) expect(result).not.toBe(prev) expect(result).not.toBe(next) }) it('should return a copy when the previous value is a different array superset', () => { const prev = [1, 2, 3] const next = [1, 2] const result = replaceEqualDeep(prev, next) expect(result).toStrictEqual(next) expect(result).not.toBe(prev) expect(result).not.toBe(next) }) it('should return the previous value when the next value is an equal empty array', () => { const prev: Array = [] const next: Array = [] expect(replaceEqualDeep(prev, next)).toBe(prev) }) it('should return the previous value when the next value is an equal empty object', () => { const prev = {} const next = {} expect(replaceEqualDeep(prev, next)).toBe(prev) }) it('should return the previous value when the next value is an equal object', () => { const prev = { a: 'a' } const next = { a: 'a' } expect(replaceEqualDeep(prev, next)).toBe(prev) }) it('should replace different values in objects', () => { const prev = { a: { b: 'b' }, c: 'c' } const next = { a: { b: 'b' }, c: 'd' } const result = replaceEqualDeep(prev, next) expect(result).toStrictEqual(next) expect(result).not.toBe(prev) expect(result).not.toBe(next) expect(result.a).toBe(prev.a) expect(result.c).toBe(next.c) }) it('should replace different values in arrays', () => { const prev = [1, { a: 'a' }, { b: { b: 'b' } }, [1]] as const const next = [1, { a: 'a' }, { b: { b: 'c' } }, [1]] as const const result = replaceEqualDeep(prev, next) expect(result).toStrictEqual(next) expect(result).not.toBe(prev) expect(result).not.toBe(next) expect(result[0]).toBe(prev[0]) expect(result[1]).toBe(prev[1]) expect(result[2]).not.toBe(next[2]) expect(result[2].b.b).toBe(next[2].b.b) expect(result[3]).toBe(prev[3]) }) it('should replace different values in arrays when the next value is a subset', () => { const prev = [{ a: 'a' }, { b: 'b' }, { c: 'c' }] const next = [{ a: 'a' }, { b: 'b' }] const result = replaceEqualDeep(prev, next) expect(result).toStrictEqual(next) expect(result).not.toBe(prev) expect(result).not.toBe(next) expect(result[0]).toBe(prev[0]) expect(result[1]).toBe(prev[1]) expect(result[2]).toBeUndefined() }) it('should replace different values in arrays when the next value is a superset', () => { const prev = [{ a: 'a' }, { b: 'b' }] const next = [{ a: 'a' }, { b: 'b' }, { c: 'c' }] const result = replaceEqualDeep(prev, next) expect(result).toStrictEqual(next) expect(result).not.toBe(prev) expect(result).not.toBe(next) expect(result[0]).toBe(prev[0]) expect(result[1]).toBe(prev[1]) expect(result[2]).toBe(next[2]) }) it('should copy objects which are not arrays or objects', () => { const prev = [{ a: 'a' }, { b: 'b' }, { c: 'c' }, 1] const next = [{ a: 'a' }, new Map(), { c: 'c' }, 2] const result = replaceEqualDeep(prev, next) expect(result).not.toBe(prev) expect(result).not.toBe(next) expect(result[0]).toBe(prev[0]) expect(result[1]).toBe(next[1]) expect(result[2]).toBe(prev[2]) expect(result[3]).toBe(next[3]) }) it('should support equal objects which are not arrays or objects', () => { const map = new Map() const prev = [map, [1]] const next = [map, [1]] const result = replaceEqualDeep(prev, next) expect(result).toBe(prev) }) it('should support non equal objects which are not arrays or objects', () => { const map1 = new Map() const map2 = new Map() const prev = [map1, [1]] const next = [map2, [1]] const result = replaceEqualDeep(prev, next) expect(result).not.toBe(prev) expect(result).not.toBe(next) expect(result[0]).toBe(next[0]) expect(result[1]).toBe(prev[1]) }) it('should support objects which are not plain arrays', () => { const prev = Object.assign([1, 2], { a: { b: 'b' }, c: 'c' }) const next = Object.assign([1, 2], { a: { b: 'b' }, c: 'c' }) const result = replaceEqualDeep(prev, next) expect(result).toBe(next) }) it('should replace all parent objects if some nested value changes', () => { const prev = { todo: { id: '1', meta: { createdAt: 0 }, state: { done: false } }, otherTodo: { id: '2', meta: { createdAt: 0 }, state: { done: true } }, } const next = { todo: { id: '1', meta: { createdAt: 0 }, state: { done: true } }, otherTodo: { id: '2', meta: { createdAt: 0 }, state: { done: true } }, } const result = replaceEqualDeep(prev, next) expect(result).toStrictEqual(next) expect(result).not.toBe(prev) expect(result).not.toBe(next) expect(result.todo).not.toBe(prev.todo) expect(result.todo).not.toBe(next.todo) expect(result.todo.id).toBe(next.todo.id) expect(result.todo.meta).toBe(prev.todo.meta) expect(result.todo.state).not.toBe(next.todo.state) expect(result.todo.state.done).toBe(next.todo.state.done) expect(result.otherTodo).toBe(prev.otherTodo) }) it('should replace all parent arrays if some nested value changes', () => { const prev = { todos: [ { id: '1', meta: { createdAt: 0 }, state: { done: false } }, { id: '2', meta: { createdAt: 0 }, state: { done: true } }, ], } const next = { todos: [ { id: '1', meta: { createdAt: 0 }, state: { done: true } }, { id: '2', meta: { createdAt: 0 }, state: { done: true } }, ], } const result = replaceEqualDeep(prev, next) expect(result).toStrictEqual(next) expect(result).not.toBe(prev) expect(result).not.toBe(next) expect(result.todos).not.toBe(prev.todos) expect(result.todos).not.toBe(next.todos) expect(result.todos[0]).not.toBe(prev.todos[0]) expect(result.todos[0]).not.toBe(next.todos[0]) expect(result.todos[0]?.id).toBe(next.todos[0]?.id) expect(result.todos[0]?.meta).toBe(prev.todos[0]?.meta) expect(result.todos[0]?.state).not.toBe(next.todos[0]?.state) expect(result.todos[0]?.state.done).toBe(next.todos[0]?.state.done) expect(result.todos[1]).toBe(prev.todos[1]) }) it('should correctly handle objects with the same number of properties and one property being undefined', () => { const obj1 = { a: 2, c: 123 } const obj2 = { a: 2, b: undefined } const result = replaceEqualDeep(obj1, obj2) expect(result).toStrictEqual(obj2) }) it('should be able to share values that contain undefined', () => { const current = [ { data: undefined, foo: true, }, ] const next = replaceEqualDeep(current, [ { data: undefined, foo: true, }, ]) expect(current).toBe(next) }) it('should return the previous value when both values are an array of undefined', () => { const current = [undefined] const next = replaceEqualDeep(current, [undefined]) expect(next).toBe(current) }) it('should return the previous value when both values are an array that contains undefined', () => { const current = [{ foo: 1 }, undefined] const next = replaceEqualDeep(current, [{ foo: 1 }, undefined]) expect(next).toBe(current) }) it('should stop structural sharing once the recursion depth exceeds the limit', () => { const nest = (depth: number, leaf: number) => { let value: any = { leaf } for (let i = 0; i < depth; i++) { value = { child: value } } return value } const prev = nest(502, 1) const next = nest(502, 2) const result = replaceEqualDeep(prev, next) let resultNode = result let nextNode = next for (let i = 0; i < 502; i++) { resultNode = resultNode.child nextNode = nextNode.child } expect(resultNode).toBe(nextNode) }) }) describe('matchMutation', () => { it('should return false if mutationKey options is undefined', () => { const filters = { mutationKey: createKey() } const queryClient = new QueryClient() const mutation = new Mutation({ client: queryClient, mutationId: 1, mutationCache: queryClient.getMutationCache(), options: {}, }) expect(matchMutation(filters, mutation)).toBe(false) }) }) describe('keepPreviousData', () => { it('should return the parameter as is', () => { const x = { a: 1, b: 2 } expect(keepPreviousData(x)).toBe(x) }) }) describe('addToArray (append)', () => { it('should add item to the end of the array', () => { const items = [1, 2, 3] const newItems = addToArray(items, 4) expect(newItems).toStrictEqual([1, 2, 3, 4]) }) it('should not exceed max if provided', () => { const items = [1, 2, 3] const newItems = addToArray(items, 4, 3) expect(newItems).toStrictEqual([2, 3, 4]) }) it('should not exceed max when items already exceed max', () => { const items = [1, 2, 3, 4, 5] const newItems = addToArray(items, 6, 3) expect(newItems).toStrictEqual([4, 5, 6]) }) it('should add item to the end of the array when max = 0', () => { const items = [1, 2, 3] const item = 4 const max = 0 expect(addToArray(items, item, max)).toStrictEqual([1, 2, 3, 4]) }) it('should add item to the end of the array when max is undefined', () => { const items = [1, 2, 3] const item = 4 const max = undefined expect(addToArray(items, item, max)).toStrictEqual([1, 2, 3, 4]) }) }) describe('addToArray (prepend)', () => { it('should add an item to the start of the array', () => { const items = [1, 2, 3] const item = 4 const newItems = addToArray(items, item, undefined, true) expect(newItems).toStrictEqual([4, 1, 2, 3]) }) it('should respect the max argument', () => { const items = [1, 2, 3] const item = 4 const max = 2 const newItems = addToArray(items, item, max, true) expect(newItems).toStrictEqual([4, 1]) }) it('should not exceed max when items already exceed max', () => { const items = [1, 2, 3, 4, 5] const newItems = addToArray(items, 6, 3, true) expect(newItems).toStrictEqual([6, 1, 2]) }) it('should not remove any items if max = 0', () => { const items = [1, 2, 3] const item = 4 const max = 0 const newItems = addToArray(items, item, max, true) expect(newItems).toStrictEqual([4, 1, 2, 3]) }) it('should not remove any items if max is undefined', () => { const items = [1, 2, 3] const item = 4 const max = undefined const newItems = addToArray(items, item, max, true) expect(newItems).toStrictEqual([4, 1, 2, 3]) }) }) describe('hashKey', () => { it('should hash primitives correctly', () => { expect(hashKey(['test'])).toStrictEqual(JSON.stringify(['test'])) expect(hashKey([123])).toStrictEqual(JSON.stringify([123])) expect(hashKey([null])).toStrictEqual(JSON.stringify([null])) }) it('should hash objects with sorted keys consistently', () => { const key1 = [{ b: 2, a: 1 }] const key2 = [{ a: 1, b: 2 }] const hash1 = hashKey(key1) const hash2 = hashKey(key2) expect(hash1).toStrictEqual(hash2) expect(hash1).toStrictEqual(JSON.stringify([{ a: 1, b: 2 }])) }) it('should hash arrays consistently', () => { const arr1 = [{ b: 2, a: 1 }, 'test', 123] const arr2 = [{ a: 1, b: 2 }, 'test', 123] expect(hashKey(arr1)).toStrictEqual(hashKey(arr2)) }) it('should handle nested objects with sorted keys', () => { const nested1 = [{ a: { d: 4, c: 3 }, b: 2 }] const nested2 = [{ b: 2, a: { c: 3, d: 4 } }] expect(hashKey(nested1)).toStrictEqual(hashKey(nested2)) }) it('should hash undefined object properties the same as missing properties', () => { const withUndefined = ['todos', { filters: undefined }] const withoutProperty = ['todos', {}] expect(hashKey(withUndefined)).toStrictEqual(hashKey(withoutProperty)) }) }) describe('isValidTimeout', () => { it('should accept valid timeout values', () => { expect(isValidTimeout(0)).toBe(true) expect(isValidTimeout(1000)).toBe(true) }) it('should reject a negative timeout value', () => { expect(isValidTimeout(-1)).toBe(false) }) it('should reject NaN', () => { expect(isValidTimeout(Number.NaN)).toBe(false) }) it('should reject Infinity', () => { expect(isValidTimeout(Number.POSITIVE_INFINITY)).toBe(false) }) it('should reject a string timeout value', () => { expect(isValidTimeout('1000')).toBe(false) }) it('should reject undefined', () => { expect(isValidTimeout(undefined)).toBe(false) }) }) describe('ensureQueryFn', () => { const context = {} as QueryFunctionContext it('should return a function that resolves to initialPromise when queryFn is missing and initialPromise is provided', async () => { const initialPromise = Promise.resolve('initial-data') const resolved = ensureQueryFn( { queryHash: '["key"]' }, { initialPromise }, ) await expect(resolved(context)).resolves.toBe('initial-data') }) it('should return a function that rejects when initialPromise rejects', async () => { const error = new Error('initial-promise-error') const initialPromise = Promise.reject(error) const resolved = ensureQueryFn( { queryHash: '["key"]' }, { initialPromise }, ) await expect(resolved(context)).rejects.toBe(error) }) it('should return a function that rejects with missing queryFn error when queryFn is set to skipToken', async () => { const consoleErrorMock = vi .spyOn(console, 'error') .mockReturnValue(undefined) const resolved = ensureQueryFn({ queryFn: skipToken, queryHash: '["skip"]', }) expect(consoleErrorMock).toHaveBeenCalledWith( expect.stringContaining( 'Attempted to invoke queryFn when set to skipToken', ), ) await expect(resolved(context)).rejects.toThrow( 'Missing queryFn: \'["skip"]\'', ) }) }) describe('shouldThrowError', () => { it('should return the result of executing throwOnError if throwOnError parameter is a function', () => { const throwOnError = (error: Error) => error.message === 'test error' expect(shouldThrowError(throwOnError, [new Error('test error')])).toBe( true, ) expect(shouldThrowError(throwOnError, [new Error('other error')])).toBe( false, ) }) it('should return throwOnError parameter itself if throwOnError is not a function', () => { expect(shouldThrowError(true, [new Error('test error')])).toBe(true) expect(shouldThrowError(false, [new Error('test error')])).toBe(false) expect(shouldThrowError(undefined, [new Error('test error')])).toBe(false) }) }) describe('addConsumeAwareSignal', () => { it('should allow page parameters to be passed to URLSearchParams', () => { const controller = new AbortController() const context = addConsumeAwareSignal( { pageParam: 'cursor' }, () => controller.signal, vi.fn(), controller.signal, ) const { signal, ...params } = context expect(signal).toBe(controller.signal) expect(new URLSearchParams(params).toString()).toBe('pageParam=cursor') }) it('should expose the signal on the query context while preserving its properties', () => { const controller = new AbortController() const key = createKey() const context = addConsumeAwareSignal( { queryKey: key, meta: undefined }, () => controller.signal, vi.fn(), ) expect(context.queryKey).toBe(key) expect(context.signal).toBe(controller.signal) }) it('should call onCancelled immediately when the signal is already aborted on first access', () => { const controller = new AbortController() controller.abort() const onCancelled = vi.fn<() => void>() const object = addConsumeAwareSignal( {}, () => controller.signal, onCancelled, ) // Access the signal to consume it void object.signal expect(onCancelled).toHaveBeenCalledTimes(1) }) it('should flag cancellation when the consumed signal aborts, mirroring streamed/infinite queries', () => { const controller = new AbortController() let cancelled = false const context = addConsumeAwareSignal( { queryKey: createKey() }, () => controller.signal, () => (cancelled = true), ) void context.signal expect(cancelled).toBe(false) controller.abort() expect(cancelled).toBe(true) }) it('should consume the signal only once across repeated accesses', () => { const controller = new AbortController() const addEventListener = vi.spyOn(controller.signal, 'addEventListener') const context = addConsumeAwareSignal( { queryKey: createKey() }, () => controller.signal, vi.fn(), ) expect(context.signal).toBe(controller.signal) expect(context.signal).toBe(controller.signal) expect(addEventListener).toHaveBeenCalledTimes(1) }) }) })