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