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

queryClient.test.tsx

1,043 lines31.1 KB

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