import { createKey, mockVisibilityState, sleep, } from '@tanstack/query-test-utils' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { CancelledError, Query, QueryCache, QueryClient, QueryObserver, dehydrate, focusManager, hydrate, noop, } from '..' import { hashQueryKeyByOptions } from '../utils' import { mockOnlineManagerIsOnline, setIsServer } from './utils' import type { QueryCacheNotifyEvent, QueryFunction, QueryFunctionContext, QueryKey, QueryObserverResult, } from '..' describe('query', () => { let queryClient: QueryClient let queryCache: QueryCache beforeEach(() => { vi.useFakeTimers() queryClient = new QueryClient() queryCache = queryClient.getQueryCache() queryClient.mount() }) afterEach(() => { queryClient.clear() vi.useRealTimers() }) it('should not let a cancelled retry pause its replacement fetch', async () => { const key = createKey() const initial = queryClient.query({ queryKey: key, queryFn: () => Promise.reject(new Error('synthetic failure')), retry: 1, retryDelay: 100, }) initial.catch(noop) await vi.advanceTimersByTimeAsync(0) await queryClient.cancelQueries({ queryKey: key }) focusManager.setFocused(false) try { const replacement = queryClient.query({ queryKey: key, queryFn: () => sleep(200).then(() => 'fresh'), }) await vi.advanceTimersByTimeAsync(100) const fetchStatus = queryClient.getQueryState(key)?.fetchStatus await vi.advanceTimersByTimeAsync(100) await expect(replacement).resolves.toBe('fresh') expect(fetchStatus).toBe('fetching') } finally { focusManager.setFocused(undefined) } }) it('should collect a cancelled query after its retry delay expires', async () => { const key = createKey() const initial = queryClient.query({ queryKey: key, queryFn: () => Promise.reject(new Error('synthetic failure')), retry: 1, retryDelay: 100, gcTime: 200, }) initial.catch(noop) await vi.advanceTimersByTimeAsync(0) await queryClient.cancelQueries({ queryKey: key }) focusManager.setFocused(false) try { await vi.advanceTimersByTimeAsync(250) expect(queryClient.getQueryState(key)).toBeUndefined() } finally { focusManager.setFocused(undefined) } }) it('should use the longest garbage collection time it has seen', async () => { const key = createKey() await queryClient .query({ queryKey: key, queryFn: () => 'data', gcTime: 100, }) .catch(noop) await queryClient .query({ queryKey: key, queryFn: () => 'data', gcTime: 200, }) .catch(noop) await queryClient .query({ queryKey: key, queryFn: () => 'data', gcTime: 10, }) .catch(noop) const query = queryCache.find({ queryKey: key })! expect(query.gcTime).toBe(200) }) it('should continue retry after focus regain and resolve all promises', async () => { const key = createKey() // make page unfocused const visibilityMock = mockVisibilityState('hidden') let count = 0 let result const promise = queryClient.query({ queryKey: key, queryFn: () => { count++ if (count === 3) { return `data${count}` } throw new Error(`error${count}`) }, retry: 3, retryDelay: 1, }) promise.then((data) => { result = data }) // Check if we do not have a result expect(result).toBeUndefined() // Check if the query is really paused await vi.advanceTimersByTimeAsync(50) expect(result).toBeUndefined() // Reset visibilityState to original value visibilityMock.mockRestore() window.dispatchEvent(new Event('visibilitychange')) // There should not be a result yet expect(result).toBeUndefined() // By now we should have a value await vi.advanceTimersByTimeAsync(50) expect(result).toBe('data3') }) it('should continue retry after reconnect and resolve all promises', async () => { const key = createKey() const onlineMock = mockOnlineManagerIsOnline(false) let count = 0 let result const promise = queryClient.query({ queryKey: key, queryFn: () => { count++ if (count === 3) { return `data${count}` } throw new Error(`error${count}`) }, retry: 3, retryDelay: 1, }) promise.then((data) => { result = data }) // Check if we do not have a result expect(result).toBeUndefined() // Check if the query is really paused await vi.advanceTimersByTimeAsync(1) expect(result).toBeUndefined() // Reset navigator to original value onlineMock.mockReturnValue(true) // trigger online event queryClient.getQueryCache().onOnline() // There should not be a result yet expect(result).toBeUndefined() // Promise should eventually be resolved await vi.advanceTimersByTimeAsync(2) expect(result).toBe('data3') }) it('should throw a CancelledError when a paused query is cancelled', async () => { const key = createKey() // make page unfocused mockVisibilityState('hidden') let count = 0 const promise = queryClient.query({ queryKey: key, queryFn: (): Promise => { count++ throw new Error(`error${count}`) }, retry: 3, retryDelay: 1, }) const query = queryCache.find({ queryKey: key })! // Check if the query is really paused await vi.advanceTimersByTimeAsync(50) expect(query.state.fetchStatus).toBe('paused') // Cancel query query.cancel() // Check if the error is set to the cancelled error await expect(promise).rejects.toBeInstanceOf(CancelledError) }) it('should cancel a paused initial fetch when the last observer unsubscribes', async () => { const key = createKey() const onlineMock = mockOnlineManagerIsOnline(false) let count = 0 const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: async ({ signal: _signal }) => { count++ await sleep(10) return `data${count}` }, }) const unsubscribe = observer.subscribe(() => undefined) const query = queryCache.find({ queryKey: key })! expect(query.state).toMatchObject({ fetchStatus: 'paused', status: 'pending', }) unsubscribe() expect(query.state).toMatchObject({ fetchStatus: 'idle', status: 'pending', }) onlineMock.mockReturnValue(true) queryClient.getQueryCache().onOnline() await vi.advanceTimersByTimeAsync(11) expect(query.state).toMatchObject({ fetchStatus: 'idle', status: 'pending', }) expect(count).toBe(0) }) it('should not throw a CancelledError when fetchQuery is in progress and the last observer unsubscribes when AbortSignal is consumed', async () => { const key = createKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => sleep(100).then(() => 'data'), }) const unsubscribe = observer.subscribe(() => undefined) await vi.advanceTimersByTimeAsync(100) expect(queryCache.find({ queryKey: key })?.state.data).toBe('data') const promise = queryClient.query({ queryKey: key, queryFn: ({ signal }) => sleep(100).then(() => 'data2' + String(signal)), }) // Ensure the fetch is in progress await vi.advanceTimersByTimeAsync(10) // Unsubscribe while fetch is in progress unsubscribe() // await queryClient.cancelQueries() await vi.advanceTimersByTimeAsync(90) // Fetch should complete successfully without throwing a CancelledError await expect(promise).resolves.toBe('data') expect(queryCache.find({ queryKey: key })?.state.data).toBe('data') }) it('should provide context to queryFn', () => { const key = createKey() const queryFn = vi .fn< ( context: QueryFunctionContext>, ) => Promise<'data'> >() .mockResolvedValue('data') void queryClient.query({ queryKey: key, queryFn }).catch(noop) expect(queryFn).toHaveBeenCalledTimes(1) const args = queryFn.mock.calls[0]![0] expect(args.pageParam).toBeUndefined() expect(args.queryKey).toStrictEqual(key) expect(args.signal).toBeInstanceOf(AbortSignal) expect(args.client).toStrictEqual(queryClient) }) it('should continue if cancellation is not supported and signal is not consumed', async () => { const key = createKey() void queryClient .query({ queryKey: key, queryFn: () => sleep(100).then(() => 'data'), }) .catch(noop) await vi.advanceTimersByTimeAsync(10) // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed const observer = new QueryObserver(queryClient, { queryKey: key, enabled: false, }) const unsubscribe = observer.subscribe(() => undefined) unsubscribe() await vi.advanceTimersByTimeAsync(90) const query = queryCache.find({ queryKey: key })! expect(query.state).toMatchObject({ data: 'data', status: 'success', dataUpdateCount: 1, }) }) it('should not continue when last observer unsubscribed if the signal was consumed', async () => { const key = createKey() void queryClient .query({ queryKey: key, queryFn: ({ signal }) => sleep(100).then(() => (signal.aborted ? 'aborted' : 'data')), }) .catch(noop) await vi.advanceTimersByTimeAsync(10) // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed const observer = new QueryObserver(queryClient, { queryKey: key, enabled: false, }) const unsubscribe = observer.subscribe(() => undefined) unsubscribe() await vi.advanceTimersByTimeAsync(90) const query = queryCache.find({ queryKey: key })! expect(query.state).toMatchObject({ data: undefined, status: 'pending', fetchStatus: 'idle', }) }) it('should provide an AbortSignal to the queryFn that provides info about the cancellation state', async () => { const key = createKey() const queryFn = vi.fn< ( context: QueryFunctionContext>, ) => Promise >() const onAbort = vi.fn<(event: Event) => void>() const abortListener = vi.fn<(event: Event) => void>() let error queryFn.mockImplementation(async ({ signal }) => { signal.onabort = onAbort signal.addEventListener('abort', abortListener) await sleep(10) signal.onabort = null signal.removeEventListener('abort', abortListener) throw new Error() }) const promise = queryClient.query({ queryKey: key, queryFn, retry: 3, retryDelay: 10, }) promise.catch((e) => { error = e }) const query = queryCache.find({ queryKey: key })! expect(queryFn).toHaveBeenCalledTimes(1) const signal = queryFn.mock.calls[0]![0].signal expect(signal.aborted).toBe(false) expect(onAbort).not.toHaveBeenCalled() expect(abortListener).not.toHaveBeenCalled() query.cancel() await vi.advanceTimersByTimeAsync(100) expect(signal.aborted).toBe(true) expect(onAbort).toHaveBeenCalledTimes(1) expect(abortListener).toHaveBeenCalledTimes(1) expect(error).toBeInstanceOf(CancelledError) }) it('should not continue if explicitly cancelled', async () => { const key = createKey() const queryFn = vi.fn<(...args: Array) => unknown>() queryFn.mockImplementation(async () => { await sleep(10) throw new Error() }) let error const promise = queryClient.query({ queryKey: key, queryFn, retry: 3, retryDelay: 10, }) promise.catch((e) => { error = e }) const query = queryCache.find({ queryKey: key })! query.cancel() await vi.advanceTimersByTimeAsync(100) expect(queryFn).toHaveBeenCalledTimes(1) expect(error).toBeInstanceOf(CancelledError) }) it('should not error if reset while pending', async () => { const key = createKey() const queryFn = vi.fn<(...args: Array) => unknown>() queryFn.mockImplementation(async () => { await sleep(10) throw new Error() }) let error queryClient .query({ queryKey: key, queryFn, retry: 3, retryDelay: 10, }) .catch((e) => { error = e }) // Ensure the query is pending const query = queryCache.find({ queryKey: key })! expect(query.state.status).toBe('pending') // Reset the query while it is pending query.reset() await vi.advanceTimersByTimeAsync(100) // The query should expect(queryFn).toHaveBeenCalledTimes(1) // have been called, expect(query.state.error).toBeNull() // not have an error, and expect(query.state.fetchStatus).toBe('idle') // not be loading any longer expect(query.state.data).toBeUndefined() // have no data // the call to fetchQuery must reject // because it was reset and not reverted // so it would resolve with undefined otherwise expect(error).toBeInstanceOf(CancelledError) }) it('should reset to default state when created from hydration', async () => { const key = createKey() const client = new QueryClient() await client .query({ queryKey: key, queryFn: () => Promise.resolve('string'), }) .catch(noop) const dehydrated = dehydrate(client) const hydrationClient = new QueryClient() hydrate(hydrationClient, dehydrated) expect(hydrationClient.getQueryData(key)).toBe('string') const query = hydrationClient.getQueryCache().find({ queryKey: key }) query?.reset() expect(hydrationClient.getQueryData(key)).toBeUndefined() }) it('should be able to refetch a cancelled query', async () => { const key = createKey() const queryFn = vi.fn<(...args: Array) => unknown>(() => sleep(50).then(() => 'data'), ) void queryClient.query({ queryKey: key, queryFn }).catch(noop) const query = queryCache.find({ queryKey: key })! await vi.advanceTimersByTimeAsync(10) query.cancel() await vi.advanceTimersByTimeAsync(100) expect(queryFn).toHaveBeenCalledTimes(1) expect(query.state.error).toBeInstanceOf(CancelledError) const result = query.fetch() await vi.advanceTimersByTimeAsync(50) await expect(result).resolves.toBe('data') expect(query.state.error).toBeNull() expect(queryFn).toHaveBeenCalledTimes(2) }) it('should not have any effect when cancelling a resolved query', async () => { const key = createKey() await queryClient .query({ queryKey: key, queryFn: () => 'data', }) .catch(noop) const query = queryCache.find({ queryKey: key })! query.cancel() await vi.advanceTimersByTimeAsync(10) expect(query.state.data).toBe('data') }) it('should not have any effect when cancelling a rejected query', async () => { const key = createKey() const error = new Error('error') await queryClient .query({ queryKey: key, queryFn: () => Promise.reject(error), }) .catch(noop) const query = queryCache.find({ queryKey: key })! query.cancel() await vi.advanceTimersByTimeAsync(10) expect(query.state.error).toBe(error) expect(query.state.error).not.toBeInstanceOf(CancelledError) }) it('should release the retryer once its fetch has settled', async () => { const key = createKey() let refetch: Promise | undefined const testCache = new QueryCache({ onSuccess: (_data, query) => { refetch ??= query.fetch() }, }) const testClient = new QueryClient({ queryCache: testCache }) const prefetch = testClient .query({ queryKey: key, queryFn: () => sleep(10).then(() => 'data'), }) .catch(noop) const query = testCache.find({ queryKey: key })! const firstPromise = query.promise expect(firstPromise).toBeDefined() await vi.advanceTimersByTimeAsync(10) await prefetch expect(query.promise).toBeDefined() expect(query.promise).not.toBe(firstPromise) await vi.advanceTimersByTimeAsync(10) await refetch expect(query.state.data).toBe('data') expect(query.promise).toBeUndefined() }) it('should keep the previous query status when refetching', async () => { const key = createKey() await queryClient .query({ queryKey: key, queryFn: () => 'data' }) .catch(noop) const query = queryCache.find({ queryKey: key })! expect(query.state.status).toBe('success') await queryClient .query({ queryKey: key, queryFn: () => Promise.reject('reject'), retry: false, }) .catch(noop) expect(query.state.status).toBe('error') void queryClient .query({ queryKey: key, queryFn: () => sleep(10).then(() => Promise.reject('reject')), retry: false, }) .catch(noop) expect(query.state.status).toBe('error') await vi.advanceTimersByTimeAsync(10) expect(query.state.status).toBe('error') }) it('should remove queries with gcTime 0 immediately after unsubscribing', async () => { const key = createKey() let count = 0 const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => { count++ return 'data' }, gcTime: 0, staleTime: Infinity, }) const unsubscribe1 = observer.subscribe(() => undefined) unsubscribe1() await vi.advanceTimersByTimeAsync(0) expect(queryCache.find({ queryKey: key })).toBeUndefined() const unsubscribe2 = observer.subscribe(() => undefined) unsubscribe2() await vi.advanceTimersByTimeAsync(0) expect(queryCache.find({ queryKey: key })).toBeUndefined() expect(count).toBe(1) }) it('should be garbage collected when unsubscribed to', async () => { const key = createKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => 'data', gcTime: 0, }) expect(queryCache.find({ queryKey: key })?.state.status).toBe('pending') const unsubscribe = observer.subscribe(() => undefined) expect(queryCache.find({ queryKey: key })?.state.status).toBe('pending') unsubscribe() await vi.advanceTimersByTimeAsync(0) expect(queryCache.find({ queryKey: key })).toBeUndefined() }) it('should be garbage collected later when unsubscribed and query is fetching', async () => { const key = createKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => sleep(20).then(() => 'data'), gcTime: 10, }) const unsubscribe = observer.subscribe(() => undefined) await vi.advanceTimersByTimeAsync(20) expect(queryCache.find({ queryKey: key })?.state.data).toBe('data') observer.refetch() unsubscribe() // unsubscribe should not remove even though gcTime has elapsed b/c query is still fetching expect(queryCache.find({ queryKey: key })?.state.data).toBe('data') // should be removed after an additional staleTime wait await vi.advanceTimersByTimeAsync(30) expect(queryCache.find({ queryKey: key })).toBeUndefined() }) it('should not be garbage collected unless there are no subscribers', async () => { const key = createKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => 'data', gcTime: 0, }) expect(queryCache.find({ queryKey: key })?.state.status).toBe('pending') const unsubscribe = observer.subscribe(() => undefined) await vi.advanceTimersByTimeAsync(100) expect(queryCache.find({ queryKey: key })?.state.data).toBe('data') unsubscribe() await vi.advanceTimersByTimeAsync(100) expect(queryCache.find({ queryKey: key })).toBeUndefined() queryClient.setQueryData(key, 'data') await vi.advanceTimersByTimeAsync(100) expect(queryCache.find({ queryKey: key })?.state.data).toBe('data') }) it('should return proper count of observers', () => { const key = createKey() const options = { queryKey: key, queryFn: () => 'data' } const observer = new QueryObserver(queryClient, options) const observer2 = new QueryObserver(queryClient, options) const observer3 = new QueryObserver(queryClient, options) const query = queryCache.find({ queryKey: key }) expect(query?.getObserversCount()).toBe(0) const unsubscribe1 = observer.subscribe(() => undefined) const unsubscribe2 = observer2.subscribe(() => undefined) const unsubscribe3 = observer3.subscribe(() => undefined) expect(query?.getObserversCount()).toBe(3) unsubscribe3() expect(query?.getObserversCount()).toBe(2) unsubscribe2() expect(query?.getObserversCount()).toBe(1) unsubscribe1() expect(query?.getObserversCount()).toBe(0) }) it('should store meta object in query', async () => { const meta = { it: 'works', } const key = createKey() await queryClient .query({ queryKey: key, queryFn: () => 'data', meta, }) .catch(noop) const query = queryCache.find({ queryKey: key })! expect(query.meta).toBe(meta) expect(query.options.meta).toBe(meta) }) it('should update meta object on change', async () => { const meta = { it: 'works', } const key = createKey() const queryFn = () => 'data' await queryClient.query({ queryKey: key, queryFn, meta }).catch(noop) await queryClient .query({ queryKey: key, queryFn, meta: undefined }) .catch(noop) const query = queryCache.find({ queryKey: key })! expect(query.meta).toBeUndefined() expect(query.options.meta).toBeUndefined() }) it('should use default meta', async () => { const meta = { it: 'works', } const key = createKey() const queryFn = () => 'data' queryClient.setQueryDefaults(key, { meta }) await queryClient.query({ queryKey: key, queryFn }).catch(noop) const query = queryCache.find({ queryKey: key })! expect(query.meta).toBe(meta) }) it('should provide meta object inside query function', async () => { const meta = { it: 'works', } const queryFn = vi.fn<() => string>(() => 'data') const key = createKey() await queryClient.query({ queryKey: key, queryFn, meta }).catch(noop) expect(queryFn).toHaveBeenCalledWith( expect.objectContaining({ meta, }), ) }) it('should refetch the observer when online method is called', () => { const key = createKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => 'data', }) const refetchSpy = vi.spyOn(observer, 'refetch') const unsubscribe = observer.subscribe(() => undefined) queryCache.onOnline() // Should refetch the observer expect(refetchSpy).toHaveBeenCalledTimes(1) unsubscribe() }) it('should not add an existing observer', async () => { const key = createKey() await queryClient .query({ queryKey: key, queryFn: () => 'data' }) .catch(noop) const query = queryCache.find({ queryKey: key })! expect(query.getObserversCount()).toBe(0) const observer = new QueryObserver(queryClient, { queryKey: key, }) expect(query.getObserversCount()).toBe(0) query.addObserver(observer) expect(query.getObserversCount()).toBe(1) query.addObserver(observer) expect(query.getObserversCount()).toBe(1) }) it('should not try to remove an observer that does not exist', async () => { const key = createKey() await queryClient .query({ queryKey: key, queryFn: () => 'data' }) .catch(noop) const query = queryCache.find({ queryKey: key })! const observer = new QueryObserver(queryClient, { queryKey: key, }) expect(query.getObserversCount()).toBe(0) const notifySpy = vi.spyOn(queryCache, 'notify') expect(() => query.removeObserver(observer)).not.toThrow() expect(notifySpy).not.toHaveBeenCalled() }) it('should notify remaining observers when one unsubscribes during an update', () => { const key = createKey() const options = { queryKey: key, enabled: false } const firstObserver = new QueryObserver(queryClient, options) const secondObserver = new QueryObserver(queryClient, options) const secondListener = vi.fn<(result: QueryObserverResult) => void>() let unsubscribeFirst: () => void = () => undefined unsubscribeFirst = firstObserver.subscribe(() => { unsubscribeFirst() }) const unsubscribeSecond = secondObserver.subscribe(secondListener) queryClient.setQueryData(key, 'data') expect(secondListener).toHaveBeenCalledTimes(1) expect(secondObserver.getCurrentResult().data).toBe('data') unsubscribeSecond() }) it('should not change state on invalidate() if already invalidated', async () => { const key = createKey() await queryClient .query({ queryKey: key, queryFn: () => 'data' }) .catch(noop) const query = queryCache.find({ queryKey: key })! query.invalidate() expect(query.state.isInvalidated).toBe(true) const previousState = query.state query.invalidate() expect(query.state).toBe(previousState) }) it('should not dispatch "fetch" from fetch if query is already fetching', async () => { const key = createKey() const queryFn = () => sleep(10).then(() => 'data') const updates: Array = [] void queryClient.query({ queryKey: key, queryFn }).catch(noop) await vi.advanceTimersByTimeAsync(10) const query = queryCache.find({ queryKey: key })! const unsubscribe = queryClient.getQueryCache().subscribe((event) => { updates.push(event.type) }) void query.fetch({ queryKey: key, queryFn, }) query.fetch({ queryKey: key, queryFn, }) await vi.advanceTimersByTimeAsync(10) expect(updates).toStrictEqual([ 'updated', // type: 'fetch' 'updated', // type: 'success' ]) unsubscribe() }) it('should throw an error from fetch if the queryFn is not defined', async () => { const key = createKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: undefined, retry: false, }) const unsubscribe = observer.subscribe(() => undefined) await vi.advanceTimersByTimeAsync(10) const query = queryCache.find({ queryKey: key })! expect(observer.getCurrentResult()).toMatchObject({ status: 'error', error: new Error(`Missing queryFn: '${query.queryHash}'`), }) unsubscribe() }) it('should dispatch an error from fetch if the queryFn returns undefined', async () => { const consoleErrorMock = vi.spyOn(console, 'error') consoleErrorMock.mockReturnValue(undefined) const key = createKey() const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => undefined, retry: false, }) let observerResult: QueryObserverResult | undefined const unsubscribe = observer.subscribe((result) => { observerResult = result }) await vi.advanceTimersByTimeAsync(10) const error = new Error(`${JSON.stringify(key)} data is undefined`) expect(observerResult).toMatchObject({ isError: true, error, }) expect(consoleErrorMock).toHaveBeenCalledWith( `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["${key}"]`, ) unsubscribe() }) it('should not retry on the server', async () => { const resetIsServer = setIsServer(true) const key = createKey() let count = 0 const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => { count++ return Promise.reject(new Error('error')) }, }) await observer.refetch() expect(count).toBe(1) resetIsServer() }) it('should use an infinite garbage collection time on the server', () => { const resetIsServer = setIsServer(true) try { const query = queryCache.build(queryClient, { queryKey: createKey(), queryFn: () => 'data', }) expect(query.gcTime).toBe(Infinity) } finally { resetIsServer() } }) it('should call initialDataUpdatedAt in constructor if defined as a function', async () => { const key = createKey() const initialDataUpdatedAtSpy = vi.fn<() => number | undefined>() await queryClient .query({ queryKey: key, queryFn: () => 'data', initialData: 'initial', initialDataUpdatedAt: initialDataUpdatedAtSpy, }) .catch(noop) expect(initialDataUpdatedAtSpy).toHaveBeenCalledWith() }) it('should work with initialDataUpdatedAt set to zero', async () => { const key = createKey() await queryClient .query({ queryKey: key, queryFn: () => 'data', staleTime: Infinity, initialData: 'initial', initialDataUpdatedAt: 0, }) .catch(noop) expect(queryCache.find({ queryKey: key })?.state).toMatchObject({ data: 'initial', status: 'success', dataUpdatedAt: 0, }) }) it('should garbage collect queries even if they never fetched', async () => { const key = createKey() queryClient.setQueryDefaults(key, { gcTime: 10 }) const fn = vi.fn<(event: QueryCacheNotifyEvent) => void>() const unsubscribe = queryClient.getQueryCache().subscribe(fn) queryClient.setQueryData(key, 'data') const query = queryClient.getQueryCache().find({ queryKey: key }) await vi.advanceTimersByTimeAsync(10) expect(fn).toHaveBeenLastCalledWith({ type: 'removed', query }) expect(queryClient.getQueryCache().findAll()).toHaveLength(0) unsubscribe() }) it('should always revert to idle state (#5968)', async () => { let mockedData = [1] const key = createKey() const queryFn = vi .fn< ( context: QueryFunctionContext>, ) => Promise >() .mockImplementation( ({ signal }) => new Promise((resolve, reject) => { const abortListener = () => { clearTimeout(timerId) reject(signal.reason) } signal.addEventListener('abort', abortListener) const timerId = setTimeout(() => { signal.removeEventListener('abort', abortListener) resolve(mockedData.join(' - ')) }, 50) }), ) const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, }) const unsubscribe = observer.subscribe(() => undefined) await vi.advanceTimersByTimeAsync(50) // let it resolve expect(observer.getCurrentResult().data).toBe('1') expect(observer.getCurrentResult().fetchStatus).toBe('idle') mockedData = [1, 2] // update "server" state in the background void queryClient.invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(5) void queryClient.invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(5) unsubscribe() // unsubscribe to simulate unmount await vi.advanceTimersByTimeAsync(5) // reverted to previous data and idle fetchStatus expect(queryCache.find({ queryKey: key })?.state).toMatchObject({ status: 'success', data: '1', fetchStatus: 'idle', }) // set up a new observer to simulate a mount of new component const newObserver = new QueryObserver(queryClient, { queryKey: key, queryFn, }) const spy = vi.fn<(data: unknown) => void>() newObserver.subscribe(({ data }) => spy(data)) await vi.advanceTimersByTimeAsync(60) // let it resolve expect(spy).toHaveBeenCalledWith('1 - 2') }) it('should not reject a promise when silently cancelled in the background', async () => { const key = createKey() let x = 0 queryClient.setQueryData(key, 'initial') const queryFn = vi .fn<() => Promise>() .mockImplementation(() => sleep(100).then(() => 'data' + x)) const promise = queryClient.query({ queryKey: key, queryFn, }) await vi.advanceTimersByTimeAsync(0) expect(queryFn).toHaveBeenCalledTimes(1) x = 1 // cancel ongoing re-fetches void queryClient.refetchQueries({ queryKey: key }, { cancelRefetch: true }) // The promise should not reject await vi.advanceTimersByTimeAsync(100) await expect(promise).resolves.toBe('data1') expect(queryFn).toHaveBeenCalledTimes(2) }) it('should resolve all imperative callers after an invalidation replaces their fetch', async () => { const key = createKey() let fetchCount = 0 const queryFn = vi.fn<() => Promise>(async () => { const data = 'data' + ++fetchCount await sleep(100) return data }) queryClient.setQueryData(key, 'initial') const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, staleTime: Infinity, }) const unsubscribe = observer.subscribe(noop) const options = { queryKey: key, queryFn } const results = Promise.allSettled([ queryClient.query(options), queryClient.query(options), ]) await vi.advanceTimersByTimeAsync(10) void queryClient.invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(100) await expect(results).resolves.toStrictEqual([ { status: 'fulfilled', value: 'data2' }, { status: 'fulfilled', value: 'data2' }, ]) expect(queryClient.getQueryData(key)).toBe('data2') expect(queryFn).toHaveBeenCalledTimes(2) unsubscribe() }) it('should resolve an imperative caller after repeated invalidations replace its fetch', async () => { const key = createKey() let fetchCount = 0 const queryFn = vi.fn<() => Promise>(async () => { const data = 'data' + ++fetchCount await sleep(100) return data }) queryClient.setQueryData(key, 'initial') const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, staleTime: Infinity, }) const unsubscribe = observer.subscribe(noop) const results = Promise.allSettled([ queryClient.query({ queryKey: key, queryFn }), ]) await vi.advanceTimersByTimeAsync(10) void queryClient.invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(10) void queryClient.invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(100) await expect(results).resolves.toStrictEqual([ { status: 'fulfilled', value: 'data3' }, ]) expect(queryClient.getQueryData(key)).toBe('data3') expect(queryFn).toHaveBeenCalledTimes(3) unsubscribe() }) it('should have an error log when queryFn data is not serializable', async () => { const consoleErrorMock = vi.spyOn(console, 'error') consoleErrorMock.mockReturnValue(undefined) const key = createKey() const queryFn = vi.fn<() => Promise>(() => sleep(10).then(() => data), ) const initialData = { foo: 'bar', } const data = { get foo(): void { return this.foo }, } void queryClient .query({ queryKey: key, queryFn, initialData, }) .catch(noop) await vi.advanceTimersByTimeAsync(10) const query = queryCache.find({ queryKey: key })! expect(queryFn).toHaveBeenCalledTimes(1) expect(query.state.status).toBe('error') expect(query.state.error?.message).toContain( 'Maximum call stack size exceeded', ) expect(consoleErrorMock).toHaveBeenCalledWith( expect.stringContaining( 'Structural sharing requires data to be JSON serializable', ), ) }) it('should have an error status when setData has any error inside', async () => { const key = createKey() const queryFn = vi.fn<() => Promise>(() => sleep(10).then(() => 'data'), ) void queryClient .query({ queryKey: key, queryFn, structuralSharing: () => { throw Error('Any error') }, }) .catch(noop) const query = queryCache.find({ queryKey: key })! expect(queryFn).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(10) expect(query.state.status).toBe('error') }) it('should use persister if provided', async () => { const key = createKey() await queryClient .query({ queryKey: key, queryFn: () => 'data', persister: () => Promise.resolve('persisted data'), }) .catch(noop) const query = queryCache.find({ queryKey: key })! expect(query.state.data).toBe('persisted data') }) it('should use queryFn from observer if not provided in options', async () => { const key = createKey() const queryFn = () => Promise.resolve('data') const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: queryFn, }) const query = new Query({ client: queryClient, queryKey: key, queryHash: hashQueryKeyByOptions(key), }) query.addObserver(observer) await query.fetch() const result = await query.state.data expect(result).toBe('data') expect(query.options.queryFn).toBe(queryFn) }) it('should log error when queryKey is not an array', async () => { const consoleErrorMock = vi.spyOn(console, 'error') const key: unknown = 'string-key' await queryClient .query({ queryKey: key as QueryKey, queryFn: () => 'data', }) .catch(noop) expect(consoleErrorMock).toHaveBeenCalledWith( "As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']", ) }) it('should call initialData function when it is a function', () => { const key = createKey() const initialDataFn = vi.fn<() => string>(() => 'initial data') const query = new Query({ client: queryClient, queryKey: key, queryHash: hashQueryKeyByOptions(key), options: { queryFn: () => 'data', initialData: initialDataFn, }, }) expect(initialDataFn).toHaveBeenCalledTimes(1) expect(query.state.data).toBe('initial data') }) it('should update initialData when Query exists without data', async () => { const key = createKey() const queryFn = vi.fn<() => Promise>(() => sleep(100).then(() => 'data'), ) const promise = queryClient .query({ queryKey: key, queryFn, staleTime: 1000, }) .catch(noop) vi.advanceTimersByTime(50) expect(queryClient.getQueryState(key)).toMatchObject({ data: undefined, status: 'pending', fetchStatus: 'fetching', }) const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, staleTime: 1000, initialData: 'initialData', initialDataUpdatedAt: 10, }) const unsubscribe = observer.subscribe(vi.fn()) expect(queryClient.getQueryState(key)).toMatchObject({ data: 'initialData', dataUpdatedAt: 10, status: 'success', fetchStatus: 'fetching', }) vi.advanceTimersByTime(50) await promise expect(queryClient.getQueryState(key)).toMatchObject({ data: 'data', status: 'success', fetchStatus: 'idle', }) expect(queryFn).toHaveBeenCalledTimes(1) unsubscribe() // resetting should get us back ot 'initialData' queryClient.getQueryCache().find({ queryKey: key })!.reset() expect(queryClient.getQueryState(key)).toMatchObject({ data: 'initialData', status: 'success', fetchStatus: 'idle', }) }) it('should not override fetching state when revert happens after new observer subscribes', async () => { const key = createKey() let count = 0 const queryFn = vi.fn>( async ({ signal: _signal }) => { // Destructure `signal` to intentionally consume it so observer-removal uses revert-cancel path await sleep(50) return 'data' + count++ }, ) const query = new Query({ client: queryClient, queryKey: key, queryHash: hashQueryKeyByOptions(key), options: { queryFn }, }) const observer1 = new QueryObserver(queryClient, { queryKey: key, queryFn, }) query.addObserver(observer1) const promise1 = query.fetch() await vi.advanceTimersByTimeAsync(10) query.removeObserver(observer1) const observer2 = new QueryObserver(queryClient, { queryKey: key, queryFn, }) query.addObserver(observer2) query.fetch() await expect(promise1).rejects.toBeInstanceOf(CancelledError) await vi.advanceTimersByTimeAsync(50) expect(query.state.fetchStatus).toBe('idle') expect(queryFn).toHaveBeenCalledTimes(2) expect(query.state).toMatchObject({ fetchStatus: 'idle', status: 'success', data: 'data1', }) }) it('should not increment dataUpdateCount when setting initialData on prefetched query', async () => { const key = createKey() const queryFn = vi.fn<() => string>().mockReturnValue('fetched-data') // First prefetch the query (creates query without data) void queryClient .query({ queryKey: key, queryFn, }) .catch(noop) const query = queryCache.find({ queryKey: key })! expect(query.state.data).toBeUndefined() expect(query.state.dataUpdateCount).toBe(0) // Now create an observer with initialData const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, initialData: 'initial-data', }) // The query should now have the initial data but dataUpdateCount should still be 0 // since this was not fetched data but initial data expect(query.state.data).toBe('initial-data') expect(query.state.dataUpdateCount).toBe(0) // Get the initial state as captured by the observer const result = observer.getCurrentResult() expect(result.data).toBe('initial-data') expect(result.isFetchedAfterMount).toBe(false) // This should be false since no actual fetch occurred // Now trigger a refetch through the observer to simulate real-world usage await observer.refetch() // After actual fetch, dataUpdateCount should increment expect(query.state.dataUpdateCount).toBe(1) expect(query.state.data).toBe('fetched-data') // And isFetchedAfterMount should now be true const updatedResult = observer.getCurrentResult() expect(updatedResult.isFetchedAfterMount).toBe(true) }) })