Open History to see the last commit
1import { sleep, queryKey, mockConsoleError } from '../../react/tests/utils'
2import {
3 InfiniteQueryObserver,
4 QueryCache,
5 QueryClient,
6 QueryFunction,
7 QueryObserver,
8 MutationObserver,
9} from '../..'
10import { focusManager, onlineManager } from '..'
11β
12describe('queryClient', () => {
13 let queryClient: QueryClient
14 let queryCache: QueryCache
15β
16 beforeEach(() => {
17 queryClient = new QueryClient()
18 queryCache = queryClient.getQueryCache()
19 queryClient.mount()
20 })
21β
22 afterEach(() => {
23 queryClient.clear()
24 })
25β
26 describe('defaultOptions', () => {
27 test('should merge defaultOptions', async () => {
28 const key = queryKey()
29β
30 const queryFn = () => 'data'
31 const testClient = new QueryClient({
32 defaultOptions: { queries: { queryFn } },
33 })
34β
35 expect(() => testClient.prefetchQuery(key)).not.toThrow()
36 })
37β
38 test('should merge defaultOptions when query is added to cache', async () => {
39 const key = queryKey()
40β
41 const testClient = new QueryClient({
42 defaultOptions: {
43 queries: { cacheTime: Infinity },
44 },
45 })
46β
47 const fetchData = () => Promise.resolve(undefined)
48 await testClient.prefetchQuery(key, fetchData)
49 const newQuery = testClient.getQueryCache().find(key)
50 expect(newQuery?.options.cacheTime).toBe(Infinity)
51 })
52β
53 test('should get defaultOptions', async () => {
54 const queryFn = () => 'data'
55 const defaultOptions = { queries: { queryFn } }
56 const testClient = new QueryClient({
57 defaultOptions,
58 })
59 expect(testClient.getDefaultOptions()).toMatchObject(defaultOptions)
60 })
61 })
62β
63 describe('setQueryDefaults', () => {
64 test('should not trigger a fetch', async () => {
65 const key = queryKey()
66 queryClient.setQueryDefaults(key, { queryFn: () => 'data' })
67 await sleep(1)
68 const data = queryClient.getQueryData(key)
69 expect(data).toBeUndefined()
70 })
71β
72 test('should be able to override defaults', async () => {
73 const key = queryKey()
74 queryClient.setQueryDefaults(key, { queryFn: () => 'data' })
75 const observer = new QueryObserver(queryClient, { queryKey: key })
76 const { data } = await observer.refetch()
77 expect(data).toBe('data')
78 })
79β
80 test('should match the query key partially', async () => {
81 const key = queryKey()
82 queryClient.setQueryDefaults([key], { queryFn: () => 'data' })
83 const observer = new QueryObserver(queryClient, {
84 queryKey: [key, 'a'],
85 })
86 const { data } = await observer.refetch()
87 expect(data).toBe('data')
88 })
89β
90 test('should not match if the query key is a subset', async () => {
91 const consoleMock = mockConsoleError()
92 const key = queryKey()
93 queryClient.setQueryDefaults([key, 'a'], { queryFn: () => 'data' })
94 const observer = new QueryObserver(queryClient, {
95 queryKey: [key],
96 retry: false,
97 enabled: false,
98 })
99 const { status } = await observer.refetch()
100 expect(status).toBe('error')
101 consoleMock.mockRestore()
102 })
103β
104 test('should also set defaults for observers', async () => {
105 const key = queryKey()
106 queryClient.setQueryDefaults(key, {
107 queryFn: () => 'data',
108 enabled: false,
109 })
110 const observer = new QueryObserver(queryClient, {
111 queryKey: [key],
112 })
113 expect(observer.getCurrentResult().status).toBe('idle')
114 })
115β
116 test('should update existing query defaults', async () => {
117 const key = queryKey()
118 const queryOptions1 = { queryFn: () => 'data' }
119 const queryOptions2 = { retry: false }
120 queryClient.setQueryDefaults(key, queryOptions1)
121 queryClient.setQueryDefaults(key, queryOptions2)
122 expect(queryClient.getQueryDefaults(key)).toMatchObject(queryOptions2)
123 })
124 })
125β
126 describe('setQueryData', () => {
127 test('should not crash if query could not be found', () => {
128 const key = queryKey()
129 const user = { userId: 1 }
130 expect(() => {
131 queryClient.setQueryData([key, user], (prevUser?: typeof user) => ({
132 ...prevUser!,
133 name: 'Edvin',
134 }))
135 }).not.toThrow()
136 })
137β
138 test('should not crash when variable is null', () => {
139 const key = queryKey()
140 queryClient.setQueryData([key, { userId: null }], 'Old Data')
141 expect(() => {
142 queryClient.setQueryData([key, { userId: null }], 'New Data')
143 }).not.toThrow()
144 })
145β
146 test('should use default options', () => {
147 const key = queryKey()
148 const testClient = new QueryClient({
149 defaultOptions: { queries: { queryKeyHashFn: () => 'someKey' } },
150 })
151 const testCache = testClient.getQueryCache()
152 testClient.setQueryData(key, 'data')
153 expect(testClient.getQueryData(key)).toBe('data')
154 expect(testCache.find(key)).toBe(testCache.get('someKey'))
155 })
156β
157 test('should create a new query if query was not found', () => {
158 const key = queryKey()
159 queryClient.setQueryData(key, 'bar')
160 expect(queryClient.getQueryData(key)).toBe('bar')
161 })
162β
163 test('should create a new query if query was not found', () => {
164 const key = queryKey()
165 queryClient.setQueryData(key, 'qux')
166 expect(queryClient.getQueryData(key)).toBe('qux')
167 })
168β
169 test('should use the same query when using similar string or array query keys', () => {
170 const key = queryKey()
171 queryClient.setQueryData(key, '1')
172 expect(queryClient.getQueryData(key)).toBe('1')
173 expect(queryClient.getQueryData([key])).toBe('1')
174 queryClient.setQueryData([key], '2')
175 expect(queryClient.getQueryData(key)).toBe('2')
176 expect(queryClient.getQueryData([key])).toBe('2')
177 queryClient.setQueryData(key, '1')
178 expect(queryClient.getQueryData(key)).toBe('1')
179 expect(queryClient.getQueryData([key])).toBe('1')
180 })
181β
182 test('should accept an update function', () => {
183 const key = queryKey()
184β
185 const updater = jest.fn(oldData => `new data + ${oldData}`)
186β
187 queryClient.setQueryData(key, 'test data')
188 queryClient.setQueryData(key, updater)
189β
190 expect(updater).toHaveBeenCalled()
191 expect(queryCache.find(key)!.state.data).toEqual('new data + test data')
192 })
193β
194 test('should use prev data if an isDataEqual function is defined and returns "true"', () => {
195 const key = queryKey()
196β
197 queryClient.setDefaultOptions({
198 queries: { isDataEqual: (_prev, data) => data === 'data' },
199 })
200 queryClient.setQueryData(key, 'prev data')
201 queryClient.setQueryData(key, 'data')
202β
203 expect(queryCache.find(key)!.state.data).toEqual('prev data')
204 })
205β
206 test('should set the new data without comparison if structuralSharing is set to false', () => {
207 const key = queryKey()
208β
209 queryClient.setDefaultOptions({
210 queries: {
211 structuralSharing: false,
212 },
213 })
214β
215 const oldData = { value: true }
216 const newData = { value: true }
217 queryClient.setQueryData(key, oldData)
218 queryClient.setQueryData(key, newData)
219β
220 expect(queryCache.find(key)!.state.data).toBe(newData)
221 })
222 })
223β
224 describe('setQueriesData', () => {
225 test('should update all existing, matching queries', () => {
226 queryClient.setQueryData(['key', 1], 1)
227 queryClient.setQueryData(['key', 2], 2)
228β
229 const result = queryClient.setQueriesData<number>('key', old => old! + 5)
230β
231 expect(result).toEqual([
232 [['key', 1], 6],
233 [['key', 2], 7],
234 ])
235 expect(queryClient.getQueryData(['key', 1])).toBe(6)
236 expect(queryClient.getQueryData(['key', 2])).toBe(7)
237 })
238β
239 test('should accept queryFilters', () => {
240 queryClient.setQueryData(['key', 1], 1)
241 queryClient.setQueryData(['key', 2], 2)
242 const query1 = queryCache.find(['key', 1])!
243β
244 const result = queryClient.setQueriesData<number>(
245 { predicate: query => query === query1 },
246 old => old! + 5
247 )
248β
249 expect(result).toEqual([[['key', 1], 6]])
250 expect(queryClient.getQueryData(['key', 1])).toBe(6)
251 expect(queryClient.getQueryData(['key', 2])).toBe(2)
252 })
253β
254 test('should not update non existing queries', () => {
255 const result = queryClient.setQueriesData<string>('key', 'data')
256β
257 expect(result).toEqual([])
258 expect(queryClient.getQueryData('key')).toBe(undefined)
259 })
260 })
261β
262 describe('getQueryData', () => {
263 test('should return the query data if the query is found', () => {
264 const key = queryKey()
265 queryClient.setQueryData([key, 'id'], 'bar')
266 expect(queryClient.getQueryData([key, 'id'])).toBe('bar')
267 })
268β
269 test('should return undefined if the query is not found', () => {
270 const key = queryKey()
271 expect(queryClient.getQueryData(key)).toBeUndefined()
272 })
273β
274 test('should match exact by default', () => {
275 const key = queryKey()
276 queryClient.setQueryData([key, 'id'], 'bar')
277 expect(queryClient.getQueryData([key])).toBeUndefined()
278 })
279 })
280β
281 describe('getQueriesData', () => {
282 test('should return the query data for all matched queries', () => {
283 const key1 = queryKey()
284 const key2 = queryKey()
285 queryClient.setQueryData([key1, 1], 1)
286 queryClient.setQueryData([key1, 2], 2)
287 queryClient.setQueryData([key2, 2], 2)
288 expect(queryClient.getQueriesData([key1])).toEqual([
289 [[key1, 1], 1],
290 [[key1, 2], 2],
291 ])
292 })
293β
294 test('should return empty array if queries are not found', () => {
295 const key = queryKey()
296 expect(queryClient.getQueriesData(key)).toEqual([])
297 })
298β
299 test('should accept query filters', () => {
300 queryClient.setQueryData(['key', 1], 1)
301 queryClient.setQueryData(['key', 2], 2)
302 const query1 = queryCache.find(['key', 1])!
303β
304 const result = queryClient.getQueriesData({
305 predicate: query => query === query1,
306 })
307β
308 expect(result).toEqual([[['key', 1], 1]])
309 })
310 })
311β
312 describe('fetchQuery', () => {
313 test('should not type-error with strict query key', async () => {
314 type StrictData = 'data'
315 type StrictQueryKey = ['strict', string]
316 const key: StrictQueryKey = ['strict', queryKey()]
317β
318 const fetchFn: QueryFunction<StrictData, StrictQueryKey> = () =>
319 Promise.resolve('data')
320β
321 await expect(
322 queryClient.fetchQuery<StrictData, any, StrictData, StrictQueryKey>(
323 key,
324 fetchFn
325 )
326 ).resolves.toEqual('data')
327 })
328β
329 // https://github.com/tannerlinsley/react-query/issues/652
330 test('should not retry by default', async () => {
331 const consoleMock = mockConsoleError()
332β
333 const key = queryKey()
334β
335 await expect(
336 queryClient.fetchQuery(key, async () => {
337 throw new Error('error')
338 })
339 ).rejects.toEqual(new Error('error'))
340β
341 consoleMock.mockRestore()
342 })
343β
344 test('should return the cached data on cache hit', async () => {
345 const key = queryKey()
346β
347 const fetchFn = () => Promise.resolve('data')
348 const first = await queryClient.fetchQuery(key, fetchFn)
349 const second = await queryClient.fetchQuery(key, fetchFn)
350β
351 expect(second).toBe(first)
352 })
353β
354 test('should be able to fetch when cache time is set to 0 and then be removed', async () => {
355 const key1 = queryKey()
356 const result = await queryClient.fetchQuery(
357 key1,
358 async () => {
359 await sleep(10)
360 return 1
361 },
362 { cacheTime: 0 }
363 )
364 const result2 = queryClient.getQueryData(key1)
365 expect(result).toEqual(1)
366 expect(result2).toEqual(undefined)
367 })
368β
369 test('should keep a query in cache if cache time is Infinity', async () => {
370 const key1 = queryKey()
371 const result = await queryClient.fetchQuery(
372 key1,
373 async () => {
374 await sleep(10)
375 return 1
376 },
377 { cacheTime: Infinity }
378 )
379 const result2 = queryClient.getQueryData(key1)
380 expect(result).toEqual(1)
381 expect(result2).toEqual(1)
382 })
383β
384 test('should not force fetch', async () => {
385 const key = queryKey()
386β
387 queryClient.setQueryData(key, 'og')
388 const fetchFn = () => Promise.resolve('new')
389 const first = await queryClient.fetchQuery(key, fetchFn, {
390 initialData: 'initial',
391 staleTime: 100,
392 })
393 expect(first).toBe('og')
394 })
395β
396 test('should only fetch if the data is older then the given stale time', async () => {
397 const key = queryKey()
398β
399 let count = 0
400 const fetchFn = () => ++count
401β
402 queryClient.setQueryData(key, count)
403 const first = await queryClient.fetchQuery(key, fetchFn, {
404 staleTime: 100,
405 })
406 await sleep(11)
407 const second = await queryClient.fetchQuery(key, fetchFn, {
408 staleTime: 10,
409 })
410 const third = await queryClient.fetchQuery(key, fetchFn, {
411 staleTime: 10,
412 })
413 await sleep(11)
414 const fourth = await queryClient.fetchQuery(key, fetchFn, {
415 staleTime: 10,
416 })
417 expect(first).toBe(0)
418 expect(second).toBe(1)
419 expect(third).toBe(1)
420 expect(fourth).toBe(2)
421 })
422 })
423β
424 describe('fetchInfiniteQuery', () => {
425 test('should not type-error with strict query key', async () => {
426 type StrictData = string
427 type StrictQueryKey = ['strict', string]
428 const key: StrictQueryKey = ['strict', queryKey()]
429β
430 const data = {
431 pages: ['data'],
432 pageParams: [undefined],
433 } as const
434β
435 const fetchFn: QueryFunction<StrictData, StrictQueryKey> = () =>
436 Promise.resolve(data.pages[0])
437β
438 await expect(
439 queryClient.fetchInfiniteQuery<
440 StrictData,
441 any,
442 StrictData,
443 StrictQueryKey
444 >(key, fetchFn)
445 ).resolves.toEqual(data)
446 })
447β
448 test('should return infinite query data', async () => {
449 const key = queryKey()
450 const result = await queryClient.fetchInfiniteQuery(
451 key,
452 ({ pageParam = 10 }) => Number(pageParam)
453 )
454 const result2 = queryClient.getQueryData(key)
455β
456 const expected = {
457 pages: [10],
458 pageParams: [undefined],
459 }
460β
461 expect(result).toEqual(expected)
462 expect(result2).toEqual(expected)
463 })
464 })
465β
466 describe('prefetchInfiniteQuery', () => {
467 test('should not type-error with strict query key', async () => {
468 type StrictData = 'data'
469 type StrictQueryKey = ['strict', string]
470 const key: StrictQueryKey = ['strict', queryKey()]
471β
472 const fetchFn: QueryFunction<StrictData, StrictQueryKey> = () =>
473 Promise.resolve('data')
474β
475 await queryClient.prefetchInfiniteQuery<
476 StrictData,
477 any,
478 StrictData,
479 StrictQueryKey
480 >(key, fetchFn)
481β
482 const result = queryClient.getQueryData(key)
483β
484 expect(result).toEqual({
485 pages: ['data'],
486 pageParams: [undefined],
487 })
488 })
489β
490 test('should return infinite query data', async () => {
491 const key = queryKey()
492β
493 await queryClient.prefetchInfiniteQuery(key, ({ pageParam = 10 }) =>
494 Number(pageParam)
495 )
496β
497 const result = queryClient.getQueryData(key)
498β
499 expect(result).toEqual({
500 pages: [10],
501 pageParams: [undefined],
502 })
503 })
504 })
505β
506 describe('prefetchQuery', () => {
507 test('should not type-error with strict query key', async () => {
508 type StrictData = 'data'
509 type StrictQueryKey = ['strict', string]
510 const key: StrictQueryKey = ['strict', queryKey()]
511β
512 const fetchFn: QueryFunction<StrictData, StrictQueryKey> = () =>
513 Promise.resolve('data')
514β
515 await queryClient.prefetchQuery<
516 StrictData,
517 any,
518 StrictData,
519 StrictQueryKey
520 >(key, fetchFn)
521β
522 const result = queryClient.getQueryData(key)
523β
524 expect(result).toEqual('data')
525 })
526β
527 test('should return undefined when an error is thrown', async () => {
528 const consoleMock = mockConsoleError()
529β
530 const key = queryKey()
531β
532 const result = await queryClient.prefetchQuery(
533 key,
534 async () => {
535 throw new Error('error')
536 },
537 {
538 retry: false,
539 }
540 )
541β
542 expect(result).toBeUndefined()
543 expect(consoleMock).toHaveBeenCalled()
544β
545 consoleMock.mockRestore()
546 })
547β
548 test('should be garbage collected after cacheTime if unused', async () => {
549 const key = queryKey()
550β
551 await queryClient.prefetchQuery(
552 key,
553 async () => {
554 return 'data'
555 },
556 { cacheTime: 10 }
557 )
558 expect(queryCache.find(key)).toBeDefined()
559 await sleep(15)
560 expect(queryCache.find(key)).not.toBeDefined()
561 })
562 })
563β
564 describe('removeQueries', () => {
565 test('should not crash when exact is provided', async () => {
566 const key = queryKey()
567β
568 const fetchFn = () => Promise.resolve('data')
569β
570 // check the query was added to the cache
571 await queryClient.prefetchQuery(key, fetchFn)
572 expect(queryCache.find(key)).toBeTruthy()
573β
574 // check the error doesn't occur
575 expect(() =>
576 queryClient.removeQueries({ queryKey: key, exact: true })
577 ).not.toThrow()
578β
579 // check query was successful removed
580 expect(queryCache.find(key)).toBeFalsy()
581 })
582 })
583β
584 describe('cancelQueries', () => {
585 test('should revert queries to their previous state', async () => {
586 const consoleMock = mockConsoleError()
587 const key1 = queryKey()
588 const key2 = queryKey()
589 const key3 = queryKey()
590 await queryClient.fetchQuery(key1, async () => {
591 return 'data'
592 })
593 try {
594 await queryClient.fetchQuery(key2, async () => {
595 return Promise.reject('err')
596 })
597 } catch {}
598 queryClient.fetchQuery(key1, async () => {
599 await sleep(1000)
600 return 'data2'
601 })
602 try {
603 queryClient.fetchQuery(key2, async () => {
604 await sleep(1000)
605 return Promise.reject('err2')
606 })
607 } catch {}
608 queryClient.fetchQuery(key3, async () => {
609 await sleep(1000)
610 return 'data3'
611 })
612 await sleep(10)
613 await queryClient.cancelQueries()
614 const state1 = queryClient.getQueryState(key1)
615 const state2 = queryClient.getQueryState(key2)
616 const state3 = queryClient.getQueryState(key3)
617 expect(state1).toMatchObject({
618 data: 'data',
619 status: 'success',
620 })
621 expect(state2).toMatchObject({
622 data: undefined,
623 error: 'err',
624 status: 'error',
625 })
626 expect(state3).toMatchObject({
627 data: undefined,
628 status: 'idle',
629 })
630 consoleMock.mockRestore()
631 })
632β
633 test('should not revert if revert option is set to false', async () => {
634 const consoleMock = mockConsoleError()
635 const key1 = queryKey()
636 await queryClient.fetchQuery(key1, async () => {
637 return 'data'
638 })
639 queryClient.fetchQuery(key1, async () => {
640 await sleep(1000)
641 return 'data2'
642 })
643 await sleep(10)
644 await queryClient.cancelQueries(key1, {}, { revert: false })
645 const state1 = queryClient.getQueryState(key1)
646 expect(state1).toMatchObject({
647 status: 'error',
648 })
649 consoleMock.mockRestore()
650 })
651 })
652β
653 describe('refetchQueries', () => {
654 test('should refetch all queries when no arguments are given', async () => {
655 const key1 = queryKey()
656 const key2 = queryKey()
657 const queryFn1 = jest.fn()
658 const queryFn2 = jest.fn()
659 await queryClient.fetchQuery(key1, queryFn1)
660 await queryClient.fetchQuery(key2, queryFn2)
661 const observer1 = new QueryObserver(queryClient, {
662 queryKey: key1,
663 enabled: false,
664 })
665 const observer2 = new QueryObserver(queryClient, {
666 queryKey: key1,
667 enabled: false,
668 })
669 observer1.subscribe()
670 observer2.subscribe()
671 await queryClient.refetchQueries()
672 observer1.destroy()
673 observer2.destroy()
674 expect(queryFn1).toHaveBeenCalledTimes(2)
675 expect(queryFn2).toHaveBeenCalledTimes(2)
676 })
677β
678 test('should be able to refetch all fresh queries', async () => {
679 const key1 = queryKey()
680 const key2 = queryKey()
681 const queryFn1 = jest.fn()
682 const queryFn2 = jest.fn()
683 await queryClient.fetchQuery(key1, queryFn1)
684 await queryClient.fetchQuery(key2, queryFn2)
685 const observer = new QueryObserver(queryClient, {
686 queryKey: key1,
687 queryFn: queryFn1,
688 staleTime: Infinity,
689 })
690 const unsubscribe = observer.subscribe()
691 await queryClient.refetchQueries({ active: true, stale: false })
692 unsubscribe()
693 expect(queryFn1).toHaveBeenCalledTimes(2)
694 expect(queryFn2).toHaveBeenCalledTimes(1)
695 })
696β
697 test('should be able to refetch all stale queries', async () => {
698 const key1 = queryKey()
699 const key2 = queryKey()
700 const queryFn1 = jest.fn()
701 const queryFn2 = jest.fn()
702 await queryClient.fetchQuery(key1, queryFn1)
703 await queryClient.fetchQuery(key2, queryFn2)
704 const observer = new QueryObserver(queryClient, {
705 queryKey: key1,
706 queryFn: queryFn1,
707 })
708 const unsubscribe = observer.subscribe()
709 queryClient.invalidateQueries(key1)
710 await queryClient.refetchQueries({ stale: true })
711 unsubscribe()
712 expect(queryFn1).toHaveBeenCalledTimes(2)
713 expect(queryFn2).toHaveBeenCalledTimes(1)
714 })
715β
716 test('should be able to refetch all stale and active queries', async () => {
717 const key1 = queryKey()
718 const key2 = queryKey()
719 const queryFn1 = jest.fn()
720 const queryFn2 = jest.fn()
721 await queryClient.fetchQuery(key1, queryFn1)
722 await queryClient.fetchQuery(key2, queryFn2)
723 queryClient.invalidateQueries(key1)
724 const observer = new QueryObserver(queryClient, {
725 queryKey: key1,
726 queryFn: queryFn1,
727 })
728 const unsubscribe = observer.subscribe()
729 await queryClient.refetchQueries({ active: true, stale: true })
730 unsubscribe()
731 expect(queryFn1).toHaveBeenCalledTimes(2)
732 expect(queryFn2).toHaveBeenCalledTimes(1)
733 })
734β
735 test('should be able to refetch all active and inactive queries', async () => {
736 const key1 = queryKey()
737 const key2 = queryKey()
738 const queryFn1 = jest.fn()
739 const queryFn2 = jest.fn()
740 await queryClient.fetchQuery(key1, queryFn1)
741 await queryClient.fetchQuery(key2, queryFn2)
742 const observer = new QueryObserver(queryClient, {
743 queryKey: key1,
744 queryFn: queryFn1,
745 staleTime: Infinity,
746 })
747 const unsubscribe = observer.subscribe()
748 await queryClient.refetchQueries()
749 unsubscribe()
750 expect(queryFn1).toHaveBeenCalledTimes(2)
751 expect(queryFn2).toHaveBeenCalledTimes(2)
752 })
753β
754 test('should be able to refetch all active and inactive queries', async () => {
755 const key1 = queryKey()
756 const key2 = queryKey()
757 const queryFn1 = jest.fn()
758 const queryFn2 = jest.fn()
759 await queryClient.fetchQuery(key1, queryFn1)
760 await queryClient.fetchQuery(key2, queryFn2)
761 const observer = new QueryObserver(queryClient, {
762 queryKey: key1,
763 queryFn: queryFn1,
764 staleTime: Infinity,
765 })
766 const unsubscribe = observer.subscribe()
767 await queryClient.refetchQueries({ active: true, inactive: true })
768 unsubscribe()
769 expect(queryFn1).toHaveBeenCalledTimes(2)
770 expect(queryFn2).toHaveBeenCalledTimes(2)
771 })
772β
773 test('should be able to refetch only active queries', async () => {
774 const key1 = queryKey()
775 const key2 = queryKey()
776 const queryFn1 = jest.fn()
777 const queryFn2 = jest.fn()
778 await queryClient.fetchQuery(key1, queryFn1)
779 await queryClient.fetchQuery(key2, queryFn2)
780 const observer = new QueryObserver(queryClient, {
781 queryKey: key1,
782 queryFn: queryFn1,
783 staleTime: Infinity,
784 })
785 const unsubscribe = observer.subscribe()
786 await queryClient.refetchQueries({ active: true })
787 unsubscribe()
788 expect(queryFn1).toHaveBeenCalledTimes(2)
789 expect(queryFn2).toHaveBeenCalledTimes(1)
790 })
791β
792 test('should be able to refetch only inactive queries', async () => {
793 const key1 = queryKey()
794 const key2 = queryKey()
795 const queryFn1 = jest.fn()
796 const queryFn2 = jest.fn()
797 await queryClient.fetchQuery(key1, queryFn1)
798 await queryClient.fetchQuery(key2, queryFn2)
799 const observer = new QueryObserver(queryClient, {
800 queryKey: key1,
801 queryFn: queryFn1,
802 staleTime: Infinity,
803 })
804 const unsubscribe = observer.subscribe()
805 await queryClient.refetchQueries({ inactive: true })
806 unsubscribe()
807 expect(queryFn1).toHaveBeenCalledTimes(1)
808 expect(queryFn2).toHaveBeenCalledTimes(2)
809 })
810β
811 test('should skip refetch for all active and inactive queries', async () => {
812 const key1 = queryKey()
813 const key2 = queryKey()
814 const queryFn1 = jest.fn()
815 const queryFn2 = jest.fn()
816 await queryClient.fetchQuery(key1, queryFn1)
817 await queryClient.fetchQuery(key2, queryFn2)
818 const observer = new QueryObserver(queryClient, {
819 queryKey: key1,
820 queryFn: queryFn1,
821 staleTime: Infinity,
822 })
823 const unsubscribe = observer.subscribe()
824 await queryClient.refetchQueries({ active: false, inactive: false })
825 unsubscribe()
826 expect(queryFn1).toHaveBeenCalledTimes(1)
827 expect(queryFn2).toHaveBeenCalledTimes(1)
828 })
829β
830 test('should throw an error if throwOnError option is set to true', async () => {
831 const consoleMock = mockConsoleError()
832 const key1 = queryKey()
833 const queryFnError = () => Promise.reject('error')
834 try {
835 await queryClient.fetchQuery({
836 queryKey: key1,
837 queryFn: queryFnError,
838 retry: false,
839 })
840 } catch {}
841 let error: any
842 try {
843 await queryClient.refetchQueries(
844 { queryKey: key1 },
845 { throwOnError: true }
846 )
847 } catch (err) {
848 error = err
849 }
850 expect(error).toEqual('error')
851 consoleMock.mockRestore()
852 })
853 })
854β
855 describe('invalidateQueries', () => {
856 test('should refetch active queries by default', async () => {
857 const key1 = queryKey()
858 const key2 = queryKey()
859 const queryFn1 = jest.fn()
860 const queryFn2 = jest.fn()
861 await queryClient.fetchQuery(key1, queryFn1)
862 await queryClient.fetchQuery(key2, queryFn2)
863 const observer = new QueryObserver(queryClient, {
864 queryKey: key1,
865 queryFn: queryFn1,
866 staleTime: Infinity,
867 })
868 const unsubscribe = observer.subscribe()
869 queryClient.invalidateQueries(key1)
870 unsubscribe()
871 expect(queryFn1).toHaveBeenCalledTimes(2)
872 expect(queryFn2).toHaveBeenCalledTimes(1)
873 })
874β
875 test('should not refetch inactive queries by default', async () => {
876 const key1 = queryKey()
877 const key2 = queryKey()
878 const queryFn1 = jest.fn()
879 const queryFn2 = jest.fn()
880 await queryClient.fetchQuery(key1, queryFn1)
881 await queryClient.fetchQuery(key2, queryFn2)
882 const observer = new QueryObserver(queryClient, {
883 queryKey: key1,
884 enabled: false,
885 staleTime: Infinity,
886 })
887 const unsubscribe = observer.subscribe()
888 queryClient.invalidateQueries(key1)
889 unsubscribe()
890 expect(queryFn1).toHaveBeenCalledTimes(1)
891 expect(queryFn2).toHaveBeenCalledTimes(1)
892 })
893β
894 test('should not refetch active queries when "refetchActive" is false', async () => {
895 const key1 = queryKey()
896 const key2 = queryKey()
897 const queryFn1 = jest.fn()
898 const queryFn2 = jest.fn()
899 await queryClient.fetchQuery(key1, queryFn1)
900 await queryClient.fetchQuery(key2, queryFn2)
901 const observer = new QueryObserver(queryClient, {
902 queryKey: key1,
903 queryFn: queryFn1,
904 staleTime: Infinity,
905 })
906 const unsubscribe = observer.subscribe()
907 queryClient.invalidateQueries(key1, {
908 refetchActive: false,
909 })
910 unsubscribe()
911 expect(queryFn1).toHaveBeenCalledTimes(1)
912 expect(queryFn2).toHaveBeenCalledTimes(1)
913 })
914β
915 test('should refetch inactive queries when "refetchInactive" is true', async () => {
916 const key1 = queryKey()
917 const key2 = queryKey()
918 const queryFn1 = jest.fn()
919 const queryFn2 = jest.fn()
920 await queryClient.fetchQuery(key1, queryFn1)
921 await queryClient.fetchQuery(key2, queryFn2)
922 const observer = new QueryObserver(queryClient, {
923 queryKey: key1,
924 queryFn: queryFn1,
925 staleTime: Infinity,
926 enabled: false,
927 })
928 const unsubscribe = observer.subscribe()
929 queryClient.invalidateQueries(key1, {
930 refetchInactive: true,
931 })
932 unsubscribe()
933 expect(queryFn1).toHaveBeenCalledTimes(2)
934 expect(queryFn2).toHaveBeenCalledTimes(1)
935 })
936β
937 test('should not refetch active queries when "refetchActive" is not provided and "active" is false', async () => {
938 const key1 = queryKey()
939 const key2 = queryKey()
940 const queryFn1 = jest.fn()
941 const queryFn2 = jest.fn()
942 await queryClient.fetchQuery(key1, queryFn1)
943 await queryClient.fetchQuery(key2, queryFn2)
944 const observer = new QueryObserver(queryClient, {
945 queryKey: key1,
946 queryFn: queryFn1,
947 staleTime: Infinity,
948 })
949 const unsubscribe = observer.subscribe()
950 queryClient.invalidateQueries(key1, {
951 active: false,
952 })
953 unsubscribe()
954 expect(queryFn1).toHaveBeenCalledTimes(1)
955 expect(queryFn2).toHaveBeenCalledTimes(1)
956 })
957β
958 test('should cancel ongoing fetches if cancelRefetch option is passed', async () => {
959 const key = queryKey()
960 const cancelFn = jest.fn()
961 const observer = new QueryObserver(queryClient, {
962 queryKey: key,
963 enabled: false,
964 initialData: 1,
965 })
966 observer.subscribe()
967β
968 queryClient.fetchQuery(key, () => {
969 const promise = new Promise(resolve => {
970 setTimeout(() => resolve(5), 10)
971 })
972 // @ts-expect-error
973 promise.cancel = cancelFn
974 return promise
975 })
976β
977 await queryClient.refetchQueries(undefined, { cancelRefetch: true })
978 observer.destroy()
979 expect(cancelFn).toHaveBeenCalledTimes(1)
980 })
981 })
982β
983 describe('resetQueries', () => {
984 test('should notify listeners when a query is reset', async () => {
985 const key = queryKey()
986β
987 const callback = jest.fn()
988β
989 await queryClient.prefetchQuery(key, () => 'data')
990β
991 queryCache.subscribe(callback)
992β
993 queryClient.resetQueries(key)
994β
995 expect(callback).toHaveBeenCalled()
996 })
997β
998 test('should reset query', async () => {
999 const key = queryKey()
1000β
1001 await queryClient.prefetchQuery(key, () => 'data')
1002β
1003 let state = queryClient.getQueryState(key)
1004 expect(state?.data).toEqual('data')
1005 expect(state?.status).toEqual('success')
1006β
1007 queryClient.resetQueries(key)
1008β
1009 state = queryClient.getQueryState(key)
1010β
1011 expect(state).toBeTruthy()
1012 expect(state?.data).toBeUndefined()
1013 expect(state?.status).toEqual('idle')
1014 })
1015β
1016 test('should reset query data to initial data if set', async () => {
1017 const key = queryKey()
1018β
1019 await queryClient.prefetchQuery(key, () => 'data', {
1020 initialData: 'initial',
1021 })
1022β
1023 let state = queryClient.getQueryState(key)
1024 expect(state?.data).toEqual('data')
1025β
1026 queryClient.resetQueries(key)
1027β
1028 state = queryClient.getQueryState(key)
1029β
1030 expect(state).toBeTruthy()
1031 expect(state?.data).toEqual('initial')
1032 })
1033β
1034 test('should refetch all active queries', async () => {
1035 const key1 = queryKey()
1036 const key2 = queryKey()
1037 const queryFn1 = jest.fn()
1038 const queryFn2 = jest.fn()
1039 const observer1 = new QueryObserver(queryClient, {
1040 queryKey: key1,
1041 queryFn: queryFn1,
1042 enabled: true,
1043 })
1044 const observer2 = new QueryObserver(queryClient, {
1045 queryKey: key2,
1046 queryFn: queryFn2,
1047 enabled: false,
1048 })
1049 observer1.subscribe()
1050 observer2.subscribe()
1051 await queryClient.resetQueries()
1052 observer2.destroy()
1053 observer1.destroy()
1054 expect(queryFn1).toHaveBeenCalledTimes(2)
1055 expect(queryFn2).toHaveBeenCalledTimes(0)
1056 })
1057 })
1058β
1059 describe('refetch only certain pages of an infinite query', () => {
1060 test('refetchQueries', async () => {
1061 const key = queryKey()
1062 let multiplier = 1
1063 const observer = new InfiniteQueryObserver<number>(queryClient, {
1064 queryKey: key,
1065 queryFn: ({ pageParam = 10 }) => Number(pageParam) * multiplier,
1066 getNextPageParam: lastPage => lastPage + 1,
1067 })
1068β
1069 await observer.fetchNextPage()
1070 await observer.fetchNextPage()
1071β
1072 expect(queryClient.getQueryData(key)).toMatchObject({
1073 pages: [10, 11],
1074 })
1075β
1076 multiplier = 2
1077β
1078 await queryClient.refetchQueries({
1079 queryKey: key,
1080 refetchPage: (_, index) => index === 0,
1081 })
1082β
1083 expect(queryClient.getQueryData(key)).toMatchObject({
1084 pages: [20, 11],
1085 })
1086 })
1087 test('invalidateQueries', async () => {
1088 const key = queryKey()
1089 let multiplier = 1
1090 const observer = new InfiniteQueryObserver<number>(queryClient, {
1091 queryKey: key,
1092 queryFn: ({ pageParam = 10 }) => Number(pageParam) * multiplier,
1093 getNextPageParam: lastPage => lastPage + 1,
1094 })
1095β
1096 await observer.fetchNextPage()
1097 await observer.fetchNextPage()
1098β
1099 expect(queryClient.getQueryData(key)).toMatchObject({
1100 pages: [10, 11],
1101 })
1102β
1103 multiplier = 2
1104β
1105 await queryClient.invalidateQueries({
1106 queryKey: key,
1107 refetchInactive: true,
1108 refetchPage: (page, _, allPages) => {
1109 return page === allPages[0]
1110 },
1111 })
1112β
1113 expect(queryClient.getQueryData(key)).toMatchObject({
1114 pages: [20, 11],
1115 })
1116 })
1117β
1118 test('resetQueries', async () => {
1119 const key = queryKey()
1120 let multiplier = 1
1121 new InfiniteQueryObserver<number>(queryClient, {
1122 queryKey: key,
1123 queryFn: ({ pageParam = 10 }) => Number(pageParam) * multiplier,
1124 getNextPageParam: lastPage => lastPage + 1,
1125 initialData: () => ({
1126 pages: [10, 11],
1127 pageParams: [10, 11],
1128 }),
1129 })
1130β
1131 expect(queryClient.getQueryData(key)).toMatchObject({
1132 pages: [10, 11],
1133 })
1134β
1135 multiplier = 2
1136β
1137 await queryClient.resetQueries({
1138 queryKey: key,
1139 inactive: true,
1140 refetchPage: (page, _, allPages) => {
1141 return page === allPages[0]
1142 },
1143 })
1144β
1145 expect(queryClient.getQueryData(key)).toMatchObject({
1146 pages: [20, 11],
1147 })
1148 })
1149 })
1150β
1151 describe('focusManager and onlineManager', () => {
1152 test('should not notify queryCache and mutationCache if not focused or online', async () => {
1153 const testClient = new QueryClient()
1154 testClient.mount()
1155β
1156 const queryCacheOnFocusSpy = jest.spyOn(
1157 testClient.getQueryCache(),
1158 'onFocus'
1159 )
1160 const queryCacheOnOnlineSpy = jest.spyOn(
1161 testClient.getQueryCache(),
1162 'onOnline'
1163 )
1164 const mutationCacheOnFocusSpy = jest.spyOn(
1165 testClient.getMutationCache(),
1166 'onFocus'
1167 )
1168 const mutationCacheOnOnlineSpy = jest.spyOn(
1169 testClient.getMutationCache(),
1170 'onOnline'
1171 )
1172β
1173 focusManager.setFocused(false)
1174 expect(queryCacheOnFocusSpy).not.toHaveBeenCalled()
1175 expect(mutationCacheOnFocusSpy).not.toHaveBeenCalled()
1176β
1177 focusManager.setFocused(true)
1178 onlineManager.setOnline(false)
1179 expect(queryCacheOnOnlineSpy).not.toHaveBeenCalled()
1180 expect(mutationCacheOnOnlineSpy).not.toHaveBeenCalled()
1181β
1182 focusManager.setFocused(true)
1183 onlineManager.setOnline(false)
1184 expect(queryCacheOnOnlineSpy).not.toHaveBeenCalled()
1185 expect(mutationCacheOnOnlineSpy).not.toHaveBeenCalled()
1186β
1187 focusManager.setFocused(false)
1188 onlineManager.setOnline(true)
1189 expect(queryCacheOnOnlineSpy).not.toHaveBeenCalled()
1190 expect(mutationCacheOnOnlineSpy).not.toHaveBeenCalled()
1191β
1192 testClient.unmount()
1193 onlineManager.setOnline(true)
1194 focusManager.setFocused(true)
1195 queryCacheOnFocusSpy.mockRestore()
1196 mutationCacheOnFocusSpy.mockRestore()
1197 queryCacheOnOnlineSpy.mockRestore()
1198 mutationCacheOnOnlineSpy.mockRestore()
1199 })
1200 })
1201β
1202 describe('cancelMutations', () => {
1203 test('should cancel mutations', async () => {
1204 const key = queryKey()
1205 const mutationObserver = new MutationObserver(queryClient, {
1206 mutationKey: key,
1207 mutationFn: async () => {
1208 await sleep(20)
1209 return 'data'
1210 },
1211 onMutate: text => text,
1212 })
1213 await mutationObserver.mutate()
1214 const mutation = queryClient
1215 .getMutationCache()
1216 .find({ mutationKey: key })!
1217 const mutationSpy = jest.spyOn(mutation, 'cancel')
1218 queryClient.cancelMutations()
1219 expect(mutationSpy).toHaveBeenCalled()
1220 mutationSpy.mockRestore()
1221 })
1222 })
1223 describe('setMutationDefaults', () => {
1224 test('should update existing mutation defaults', () => {
1225 const key = queryKey()
1226 const mutationOptions1 = { mutationFn: async () => 'data' }
1227 const mutationOptions2 = { retry: false }
1228 queryClient.setMutationDefaults(key, mutationOptions1)
1229 queryClient.setMutationDefaults(key, mutationOptions2)
1230 expect(queryClient.getMutationDefaults(key)).toMatchObject(
1231 mutationOptions2
1232 )
1233 })
1234 })
1235})