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

queryObserver.test.tsx

723 lines20.1 KB

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