Open History to see the last commit
1import {
2 sleep,
3 queryKey,
4 mockConsoleError,
5 expectType,
6} from '../../react/tests/utils'
7import {
8 QueryClient,
9 QueryObserver,
10 QueryObserverResult,
11 focusManager,
12} from '../..'
13β
14describe('queryObserver', () => {
15 let queryClient: QueryClient
16β
17 beforeEach(() => {
18 queryClient = new QueryClient()
19 queryClient.mount()
20 })
21β
22 afterEach(() => {
23 queryClient.clear()
24 })
25β
26 test('should trigger a fetch when subscribed', async () => {
27 const key = queryKey()
28 const queryFn = jest.fn()
29 const observer = new QueryObserver(queryClient, { queryKey: key, queryFn })
30 const unsubscribe = observer.subscribe()
31 await sleep(1)
32 unsubscribe()
33 expect(queryFn).toHaveBeenCalledTimes(1)
34 })
35β
36 test('should notify when switching query', async () => {
37 const key1 = queryKey()
38 const key2 = queryKey()
39 const results: QueryObserverResult[] = []
40 const observer = new QueryObserver(queryClient, {
41 queryKey: key1,
42 queryFn: () => 1,
43 })
44 const unsubscribe = observer.subscribe(result => {
45 results.push(result)
46 })
47 await sleep(1)
48 observer.setOptions({ queryKey: key2, queryFn: () => 2 })
49 await sleep(1)
50 unsubscribe()
51 expect(results.length).toBe(4)
52 expect(results[0]).toMatchObject({ data: undefined, status: 'loading' })
53 expect(results[1]).toMatchObject({ data: 1, status: 'success' })
54 expect(results[2]).toMatchObject({ data: undefined, status: 'loading' })
55 expect(results[3]).toMatchObject({ data: 2, status: 'success' })
56 })
57β
58 test('should be able to fetch with a selector', async () => {
59 const key = queryKey()
60 const observer = new QueryObserver(queryClient, {
61 queryKey: key,
62 queryFn: () => ({ count: 1 }),
63 select: data => ({ myCount: data.count }),
64 })
65 let observerResult
66 const unsubscribe = observer.subscribe(result => {
67 expectType<QueryObserverResult<{ myCount: number }>>(result)
68 observerResult = result
69 })
70 await sleep(1)
71 unsubscribe()
72 expect(observerResult).toMatchObject({ data: { myCount: 1 } })
73 })
74β
75 test('should be able to fetch with a selector using the fetch method', async () => {
76 const key = queryKey()
77 const observer = new QueryObserver(queryClient, {
78 queryKey: key,
79 queryFn: () => ({ count: 1 }),
80 select: data => ({ myCount: data.count }),
81 })
82 const observerResult = await observer.refetch()
83 expectType<{ myCount: number } | undefined>(observerResult.data)
84 expect(observerResult.data).toMatchObject({ myCount: 1 })
85 })
86β
87 test('should be able to fetch with a selector and object syntax', async () => {
88 const key = queryKey()
89 const observer = new QueryObserver(queryClient, {
90 queryKey: key,
91 queryFn: () => ({ count: 1 }),
92 select: data => ({ myCount: data.count }),
93 })
94 let observerResult
95 const unsubscribe = observer.subscribe(result => {
96 observerResult = result
97 })
98 await sleep(1)
99 unsubscribe()
100 expect(observerResult).toMatchObject({ data: { myCount: 1 } })
101 })
102β
103 test('should run the selector again if the data changed', async () => {
104 const key = queryKey()
105 let count = 0
106 const observer = new QueryObserver(queryClient, {
107 queryKey: key,
108 queryFn: () => ({ count }),
109 select: data => {
110 count++
111 return { myCount: data.count }
112 },
113 })
114 const observerResult1 = await observer.refetch()
115 const observerResult2 = await observer.refetch()
116 expect(count).toBe(2)
117 expect(observerResult1.data).toMatchObject({ myCount: 0 })
118 expect(observerResult2.data).toMatchObject({ myCount: 1 })
119 })
120β
121 test('should run the selector again if the selector changed', async () => {
122 const key = queryKey()
123 let count = 0
124 const results: QueryObserverResult[] = []
125 const queryFn = () => ({ count: 1 })
126 const select1 = (data: ReturnType<typeof queryFn>) => {
127 count++
128 return { myCount: data.count }
129 }
130 const select2 = (_data: ReturnType<typeof queryFn>) => {
131 count++
132 return { myCount: 99 }
133 }
134 const observer = new QueryObserver(queryClient, {
135 queryKey: key,
136 queryFn,
137 select: select1,
138 })
139 const unsubscribe = observer.subscribe(result => {
140 results.push(result)
141 })
142 await sleep(1)
143 observer.setOptions({
144 queryKey: key,
145 queryFn,
146 select: select2,
147 })
148 await sleep(1)
149 await observer.refetch()
150 unsubscribe()
151 expect(count).toBe(2)
152 expect(results.length).toBe(5)
153 expect(results[0]).toMatchObject({
154 status: 'loading',
155 isFetching: true,
156 data: undefined,
157 })
158 expect(results[1]).toMatchObject({
159 status: 'success',
160 isFetching: false,
161 data: { myCount: 1 },
162 })
163 expect(results[2]).toMatchObject({
164 status: 'success',
165 isFetching: false,
166 data: { myCount: 99 },
167 })
168 expect(results[3]).toMatchObject({
169 status: 'success',
170 isFetching: true,
171 data: { myCount: 99 },
172 })
173 expect(results[4]).toMatchObject({
174 status: 'success',
175 isFetching: false,
176 data: { myCount: 99 },
177 })
178 })
179β
180 test('should not run the selector again if the data and selector did not change', async () => {
181 const key = queryKey()
182 let count = 0
183 const results: QueryObserverResult[] = []
184 const queryFn = () => ({ count: 1 })
185 const select = (data: ReturnType<typeof queryFn>) => {
186 count++
187 return { myCount: data.count }
188 }
189 const observer = new QueryObserver(queryClient, {
190 queryKey: key,
191 queryFn,
192 select,
193 })
194 const unsubscribe = observer.subscribe(result => {
195 results.push(result)
196 })
197 await sleep(1)
198 observer.setOptions({
199 queryKey: key,
200 queryFn,
201 select,
202 })
203 await sleep(1)
204 await observer.refetch()
205 unsubscribe()
206 expect(count).toBe(1)
207 expect(results.length).toBe(4)
208 expect(results[0]).toMatchObject({
209 status: 'loading',
210 isFetching: true,
211 data: undefined,
212 })
213 expect(results[1]).toMatchObject({
214 status: 'success',
215 isFetching: false,
216 data: { myCount: 1 },
217 })
218 expect(results[2]).toMatchObject({
219 status: 'success',
220 isFetching: true,
221 data: { myCount: 1 },
222 })
223 expect(results[3]).toMatchObject({
224 status: 'success',
225 isFetching: false,
226 data: { myCount: 1 },
227 })
228 })
229β
230 test('should not run the selector again if the data did not change', async () => {
231 const key = queryKey()
232 let count = 0
233 const observer = new QueryObserver(queryClient, {
234 queryKey: key,
235 queryFn: () => ({ count: 1 }),
236 select: data => {
237 count++
238 return { myCount: data.count }
239 },
240 })
241 const observerResult1 = await observer.refetch()
242 const observerResult2 = await observer.refetch()
243 expect(count).toBe(1)
244 expect(observerResult1.data).toMatchObject({ myCount: 1 })
245 expect(observerResult2.data).toMatchObject({ myCount: 1 })
246 })
247β
248 test('should always run the selector again if selector throws an error and selector is not referentially stable', async () => {
249 const consoleMock = mockConsoleError()
250 const key = queryKey()
251 const results: QueryObserverResult[] = []
252 const queryFn = () => ({ count: 1 })
253 const observer = new QueryObserver(queryClient, {
254 queryKey: key,
255 queryFn,
256 select: () => {
257 throw new Error('selector error')
258 },
259 })
260 const unsubscribe = observer.subscribe(result => {
261 results.push(result)
262 })
263 await sleep(1)
264 await observer.refetch()
265 unsubscribe()
266 expect(results.length).toBe(4)
267 expect(results[0]).toMatchObject({
268 status: 'loading',
269 isFetching: true,
270 data: undefined,
271 })
272 expect(results[1]).toMatchObject({
273 status: 'error',
274 isFetching: false,
275 data: undefined,
276 })
277 expect(results[2]).toMatchObject({
278 status: 'error',
279 isFetching: true,
280 data: undefined,
281 })
282 expect(results[3]).toMatchObject({
283 status: 'error',
284 isFetching: false,
285 data: undefined,
286 })
287 consoleMock.mockRestore()
288 })
289β
290 test('should return stale data if selector throws an error', async () => {
291 const consoleMock = mockConsoleError()
292 const key = queryKey()
293 const results: QueryObserverResult[] = []
294 let shouldError = false
295 const error = new Error('select error')
296 const observer = new QueryObserver(queryClient, {
297 queryKey: key,
298 queryFn: () => (shouldError ? 2 : 1),
299 select: num => {
300 if (shouldError) {
301 throw error
302 }
303 shouldError = true
304 return String(num)
305 },
306 })
307β
308 const unsubscribe = observer.subscribe(result => {
309 results.push(result)
310 })
311 await sleep(10)
312 await observer.refetch()
313 unsubscribe()
314β
315 expect(results.length).toBe(4)
316 expect(results[0]).toMatchObject({
317 status: 'loading',
318 isFetching: true,
319 data: undefined,
320 error: null,
321 })
322 expect(results[1]).toMatchObject({
323 status: 'success',
324 isFetching: false,
325 data: '1',
326 error: null,
327 })
328 expect(results[2]).toMatchObject({
329 status: 'success',
330 isFetching: true,
331 data: '1',
332 error: null,
333 })
334 expect(results[3]).toMatchObject({
335 status: 'error',
336 isFetching: false,
337 data: '1',
338 error,
339 })
340β
341 consoleMock.mockRestore()
342 })
343β
344 test('should structurally share the selector', async () => {
345 const key = queryKey()
346 let count = 0
347 const observer = new QueryObserver(queryClient, {
348 queryKey: key,
349 queryFn: () => ({ count: ++count }),
350 select: () => ({ myCount: 1 }),
351 })
352 const observerResult1 = await observer.refetch()
353 const observerResult2 = await observer.refetch()
354 expect(count).toBe(2)
355 expect(observerResult1.data).toBe(observerResult2.data)
356 })
357β
358 test('should not trigger a fetch when subscribed and disabled', async () => {
359 const key = queryKey()
360 const queryFn = jest.fn()
361 const observer = new QueryObserver(queryClient, {
362 queryKey: key,
363 queryFn,
364 enabled: false,
365 })
366 const unsubscribe = observer.subscribe()
367 await sleep(1)
368 unsubscribe()
369 expect(queryFn).toHaveBeenCalledTimes(0)
370 })
371β
372 test('should not trigger a fetch when not subscribed', async () => {
373 const key = queryKey()
374 const queryFn = jest.fn()
375 new QueryObserver(queryClient, { queryKey: key, queryFn })
376 await sleep(1)
377 expect(queryFn).toHaveBeenCalledTimes(0)
378 })
379β
380 test('should be able to watch a query without defining a query function', async () => {
381 const key = queryKey()
382 const queryFn = jest.fn()
383 const callback = jest.fn()
384 const observer = new QueryObserver(queryClient, {
385 queryKey: key,
386 enabled: false,
387 })
388 const unsubscribe = observer.subscribe(callback)
389 await queryClient.fetchQuery(key, queryFn)
390 unsubscribe()
391 expect(queryFn).toHaveBeenCalledTimes(1)
392 expect(callback).toHaveBeenCalledTimes(2)
393 })
394β
395 test('should accept unresolved query config in update function', async () => {
396 const key = queryKey()
397 const queryFn = jest.fn()
398 const observer = new QueryObserver(queryClient, {
399 queryKey: key,
400 enabled: false,
401 })
402 const results: QueryObserverResult<unknown>[] = []
403 const unsubscribe = observer.subscribe(x => {
404 results.push(x)
405 })
406 observer.setOptions({ enabled: false, staleTime: 10 })
407 await queryClient.fetchQuery(key, queryFn)
408 await sleep(100)
409 unsubscribe()
410 expect(queryFn).toHaveBeenCalledTimes(1)
411 expect(results.length).toBe(3)
412 expect(results[0]).toMatchObject({ isStale: true })
413 expect(results[1]).toMatchObject({ isStale: false })
414 expect(results[2]).toMatchObject({ isStale: true })
415 })
416β
417 test('should be able to handle multiple subscribers', async () => {
418 const key = queryKey()
419 const queryFn = jest.fn().mockReturnValue('data')
420 const observer = new QueryObserver<string>(queryClient, {
421 queryKey: key,
422 enabled: false,
423 })
424 const results1: QueryObserverResult<string>[] = []
425 const results2: QueryObserverResult<string>[] = []
426 const unsubscribe1 = observer.subscribe(x => {
427 results1.push(x)
428 })
429 const unsubscribe2 = observer.subscribe(x => {
430 results2.push(x)
431 })
432 await queryClient.fetchQuery(key, queryFn)
433 await sleep(50)
434 unsubscribe1()
435 unsubscribe2()
436 expect(queryFn).toHaveBeenCalledTimes(1)
437 expect(results1.length).toBe(2)
438 expect(results2.length).toBe(2)
439 expect(results1[0]).toMatchObject({ data: undefined })
440 expect(results1[1]).toMatchObject({ data: 'data' })
441 expect(results2[0]).toMatchObject({ data: undefined })
442 expect(results2[1]).toMatchObject({ data: 'data' })
443 })
444β
445 test('should be able to resolve a promise', async () => {
446 const key = queryKey()
447 const queryFn = jest.fn().mockReturnValue('data')
448 const observer = new QueryObserver<string>(queryClient, {
449 queryKey: key,
450 enabled: false,
451 })
452 let value
453 observer.getNextResult().then(x => {
454 value = x
455 })
456 queryClient.prefetchQuery(key, queryFn)
457 await sleep(50)
458 expect(queryFn).toHaveBeenCalledTimes(1)
459 expect(value).toMatchObject({ data: 'data' })
460 })
461β
462 test('should be able to resolve a promise with an error', async () => {
463 const consoleMock = mockConsoleError()
464 const key = queryKey()
465 const observer = new QueryObserver<string>(queryClient, {
466 queryKey: key,
467 enabled: false,
468 })
469 let error
470 observer.getNextResult({ throwOnError: true }).catch(e => {
471 error = e
472 })
473 queryClient.prefetchQuery(key, () => Promise.reject('reject'))
474 await sleep(50)
475 expect(error).toEqual('reject')
476 consoleMock.mockRestore()
477 })
478β
479 test('should stop retry when unsubscribing', async () => {
480 const consoleMock = mockConsoleError()
481 const key = queryKey()
482 let count = 0
483 const observer = new QueryObserver(queryClient, {
484 queryKey: key,
485 queryFn: () => {
486 count++
487 return Promise.reject('reject')
488 },
489 retry: 10,
490 retryDelay: 50,
491 })
492 const unsubscribe = observer.subscribe()
493 await sleep(70)
494 unsubscribe()
495 await sleep(200)
496 expect(count).toBe(2)
497 consoleMock.mockRestore()
498 })
499β
500 test('should clear interval when unsubscribing to a refetchInterval query', async () => {
501 const key = queryKey()
502β
503 const fetchData = () => Promise.resolve('data')
504 const observer = new QueryObserver(queryClient, {
505 queryKey: key,
506 queryFn: fetchData,
507 cacheTime: 0,
508 refetchInterval: 1,
509 })
510 const unsubscribe = observer.subscribe()
511 // @ts-expect-error
512 expect(observer.refetchIntervalId).not.toBeUndefined()
513 unsubscribe()
514 // @ts-expect-error
515 expect(observer.refetchIntervalId).toBeUndefined()
516 await sleep(10)
517 expect(queryClient.getQueryCache().find(key)).toBeUndefined()
518 })
519β
520 test('uses placeholderData as non-cache data when loading a query with no data', async () => {
521 const key = queryKey()
522 const observer = new QueryObserver(queryClient, {
523 queryKey: key,
524 queryFn: () => 'data',
525 placeholderData: 'placeholder',
526 })
527β
528 expect(observer.getCurrentResult()).toMatchObject({
529 status: 'success',
530 data: 'placeholder',
531 })
532β
533 const results: QueryObserverResult<unknown>[] = []
534β
535 const unsubscribe = observer.subscribe(x => {
536 results.push(x)
537 })
538β
539 await sleep(10)
540 unsubscribe()
541β
542 expect(results.length).toBe(2)
543 expect(results[0]).toMatchObject({ status: 'success', data: 'placeholder' })
544 expect(results[1]).toMatchObject({ status: 'success', data: 'data' })
545 })
546β
547 test('the retrier should not throw an error when reject if the retrier is already resolved', async () => {
548 const consoleMock = mockConsoleError()
549 const key = queryKey()
550 let count = 0
551β
552 const observer = new QueryObserver(queryClient, {
553 queryKey: key,
554 queryFn: () => {
555 count++
556 return Promise.reject(`reject ${count}`)
557 },
558 retry: 1,
559 retryDelay: 20,
560 })
561β
562 const unsubscribe = observer.subscribe()
563β
564 // Simulate a race condition when an unsubscribe and a retry occur.
565 await sleep(20)
566 unsubscribe()
567β
568 // A second reject is triggered for the retry
569 // but the retryer has already set isResolved to true
570 // so it does nothing and no error is thrown
571β
572 // Should not log an error
573 queryClient.clear()
574 await sleep(40)
575 expect(consoleMock).not.toHaveBeenNthCalledWith(1, 'reject 1')
576β
577 consoleMock.mockRestore()
578 })
579β
580 test('should throw an error if enabled option type is not valid', async () => {
581 const key = queryKey()
582β
583 expect(
584 () =>
585 new QueryObserver(queryClient, {
586 queryKey: key,
587 queryFn: () => 'data',
588 //@ts-expect-error
589 enabled: null,
590 })
591 ).toThrowError('Expected enabled to be a boolean')
592 })
593β
594 test('getCurrentQuery should return the current query', async () => {
595 const key = queryKey()
596β
597 const observer = new QueryObserver(queryClient, {
598 queryKey: key,
599 queryFn: () => 'data',
600 })
601β
602 expect(observer.getCurrentQuery().queryKey).toEqual(key)
603 })
604β
605 test('should throw an error if throwOnError option is true', async () => {
606 const key = queryKey()
607 const consoleMock = mockConsoleError()
608β
609 const observer = new QueryObserver(queryClient, {
610 queryKey: key,
611 queryFn: () => Promise.reject('error'),
612 retry: false,
613 })
614β
615 let error: string | null = null
616 try {
617 await observer.refetch({ throwOnError: true })
618 } catch (err) {
619 error = err as string
620 }
621β
622 expect(error).toEqual('error')
623β
624 consoleMock.mockRestore()
625 })
626β
627 test('should not refetch in background if refetchIntervalInBackground is false', async () => {
628 const key = queryKey()
629 const queryFn = jest.fn()
630β
631 focusManager.setFocused(false)
632 const observer = new QueryObserver(queryClient, {
633 queryKey: key,
634 queryFn,
635 refetchIntervalInBackground: false,
636 refetchInterval: 10,
637 })
638β
639 const unsubscribe = observer.subscribe()
640 await sleep(30)
641β
642 expect(queryFn).toHaveBeenCalledTimes(1)
643β
644 // Clean-up
645 unsubscribe()
646 focusManager.setFocused(true)
647 })
648β
649 test('should not use replaceEqualDeep for select value when structuralSharing option is true', async () => {
650 const key = queryKey()
651β
652 const data = { value: 'data' }
653 const selectedData = { value: 'data' }
654β
655 const observer = new QueryObserver(queryClient, {
656 queryKey: key,
657 queryFn: () => data,
658 select: () => data,
659 })
660β
661 const unsubscribe = observer.subscribe()
662β
663 await sleep(10)
664 expect(observer.getCurrentResult().data).toBe(data)
665β
666 observer.setOptions({
667 queryKey: key,
668 queryFn: () => data,
669 structuralSharing: false,
670 select: () => selectedData,
671 })
672β
673 await observer.refetch({ queryKey: key })
674 expect(observer.getCurrentResult().data).toBe(selectedData)
675β
676 unsubscribe()
677 })
678β
679 test('select function error using placeholderdata should log an error', () => {
680 const key = queryKey()
681 const consoleMock = mockConsoleError()
682β
683 new QueryObserver(queryClient, {
684 queryKey: key,
685 queryFn: () => 'data',
686 placeholderData: 'placeholderdata',
687 select: () => {
688 throw new Error('error')
689 },
690 })
691β
692 expect(consoleMock).toHaveBeenNthCalledWith(1, new Error('error'))
693β
694 consoleMock.mockRestore()
695 })
696β
697 test('should not use replaceEqualDeep for select value when structuralSharing option is true and placeholderdata is defined', () => {
698 const key = queryKey()
699β
700 const data = { value: 'data' }
701 const selectedData1 = { value: 'data' }
702 const selectedData2 = { value: 'data' }
703 const placeholderData1 = { value: 'data' }
704 const placeholderData2 = { value: 'data' }
705β
706 const observer = new QueryObserver(queryClient, {
707 queryKey: key,
708 queryFn: () => data,
709 select: () => data,
710 })
711β
712 observer.setOptions({
713 queryKey: key,
714 queryFn: () => data,
715 select: () => {
716 if (true) return selectedData1
717 },
718 placeholderData: placeholderData1,
719 })
720β
721 observer.setOptions({
722 queryKey: key,
723 queryFn: () => data,
724 select: () => {
725 return selectedData2
726 },
727 placeholderData: placeholderData2,
728 structuralSharing: false,
729 })
730β
731 expect(observer.getCurrentResult().data).toBe(selectedData2)
732 })
733β
734 test('should not use an undefined value returned by select as placeholderdata', () => {
735 const key = queryKey()
736β
737 const data = { value: 'data' }
738 const selectedData = { value: 'data' }
739 const placeholderData1 = { value: 'data' }
740 const placeholderData2 = { value: 'data' }
741β
742 const observer = new QueryObserver(queryClient, {
743 queryKey: key,
744 queryFn: () => data,
745 select: () => data,
746 })
747β
748 observer.setOptions({
749 queryKey: key,
750 queryFn: () => data,
751 select: () => {
752 if (true) return selectedData
753 },
754 placeholderData: placeholderData1,
755 })
756β
757 expect(observer.getCurrentResult().isPlaceholderData).toBe(true)
758β
759 observer.setOptions({
760 queryKey: key,
761 queryFn: () => data,
762 //@ts-expect-error
763 select: () => undefined,
764 placeholderData: placeholderData2,
765 })
766β
767 expect(observer.getCurrentResult().isPlaceholderData).toBe(false)
768 })
769β
770 test('updateResult should not notify cache listeners if cache option is false', async () => {
771 const key = queryKey()
772β
773 const data1 = { value: 'data 1' }
774 const data2 = { value: 'data 2' }
775β
776 await queryClient.prefetchQuery(key, () => data1)
777 const observer = new QueryObserver(queryClient, {
778 queryKey: key,
779 })
780 await queryClient.prefetchQuery(key, () => data2)
781β
782 const spy = jest.fn()
783 const unsubscribe = queryClient.getQueryCache().subscribe(spy)
784 observer.updateResult({ cache: false })
785β
786 expect(spy).toHaveBeenCalledTimes(0)
787β
788 unsubscribe()
789 })
790β
791 test('should not notify observer when the stale timeout expires and the current result is stale', async () => {
792 const key = queryKey()
793 const queryFn = () => 'data'
794β
795 await queryClient.prefetchQuery(key, queryFn)
796 const observer = new QueryObserver(queryClient, {
797 queryKey: key,
798 queryFn,
799 staleTime: 20,
800 })
801β
802 const spy = jest.fn()
803 const unsubscribe = observer.subscribe(spy)
804 await queryClient.refetchQueries(key)
805 await sleep(10)
806β
807 // Force isStale to true
808 // because no use case has been found to reproduce this condition
809 // @ts-ignore
810 observer['currentResult'].isStale = true
811 spy.mockReset()
812 await sleep(30)
813 expect(spy).not.toHaveBeenCalled()
814β
815 unsubscribe()
816 })
817})