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

queryClient.test.tsx

1,472 lines46.1 KB

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