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