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} 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 })
1043})