Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { queryKey, sleep } from '@tanstack/query-test-utils'
3import { QueriesObserver, QueryClient, QueryObserver } from '..'
4import type { QueryObserverResult } from '..'
5β
6describe('queriesObserver', () => {
7 let queryClient: QueryClient
8β
9 beforeEach(() => {
10 vi.useFakeTimers()
11 queryClient = new QueryClient()
12 queryClient.mount()
13 })
14β
15 afterEach(() => {
16 queryClient.clear()
17 vi.useRealTimers()
18 })
19β
20 it('should return an array with all query results', async () => {
21 const key1 = queryKey()
22 const key2 = queryKey()
23 const queryFn1 = vi.fn().mockReturnValue(1)
24 const queryFn2 = vi.fn().mockReturnValue(2)
25 const observer = new QueriesObserver(queryClient, [
26 { queryKey: key1, queryFn: queryFn1 },
27 { queryKey: key2, queryFn: queryFn2 },
28 ])
29 let observerResult
30 const unsubscribe = observer.subscribe((result) => {
31 observerResult = result
32 })
33β
34 await vi.advanceTimersByTimeAsync(0)
35β
36 unsubscribe()
37β
38 expect(observerResult).toMatchObject([{ data: 1 }, { data: 2 }])
39 })
40β
41 it('should return current queries via getQueries', async () => {
42 const key1 = queryKey()
43 const key2 = queryKey()
44 const queryFn1 = vi.fn().mockReturnValue(1)
45 const queryFn2 = vi.fn().mockReturnValue(2)
46 const observer = new QueriesObserver(queryClient, [
47 { queryKey: key1, queryFn: queryFn1 },
48 { queryKey: key2, queryFn: queryFn2 },
49 ])
50 const unsubscribe = observer.subscribe(() => undefined)
51β
52 await vi.advanceTimersByTimeAsync(0)
53β
54 const queries = observer.getQueries()
55β
56 expect(queries).toHaveLength(2)
57 expect(queries[0]?.queryKey).toEqual(key1)
58 expect(queries[1]?.queryKey).toEqual(key2)
59β
60 unsubscribe()
61 })
62β
63 it('should update when a query updates', async () => {
64 const key1 = queryKey()
65 const key2 = queryKey()
66 const queryFn1 = vi.fn().mockReturnValue(1)
67 const queryFn2 = vi.fn().mockReturnValue(2)
68 const observer = new QueriesObserver(queryClient, [
69 { queryKey: key1, queryFn: queryFn1 },
70 { queryKey: key2, queryFn: queryFn2 },
71 ])
72 const results: Array<Array<QueryObserverResult>> = []
73 results.push(observer.getCurrentResult())
74 const unsubscribe = observer.subscribe((result) => {
75 results.push(result)
76 })
77β
78 await vi.advanceTimersByTimeAsync(0)
79 queryClient.setQueryData(key2, 3)
80 unsubscribe()
81β
82 expect(results.length).toBe(6)
83 expect(results[0]).toMatchObject([
84 { status: 'pending', fetchStatus: 'idle', data: undefined },
85 { status: 'pending', fetchStatus: 'idle', data: undefined },
86 ])
87 expect(results[1]).toMatchObject([
88 { status: 'pending', fetchStatus: 'fetching', data: undefined },
89 { status: 'pending', fetchStatus: 'idle', data: undefined },
90 ])
91 expect(results[2]).toMatchObject([
92 { status: 'pending', fetchStatus: 'fetching', data: undefined },
93 { status: 'pending', fetchStatus: 'fetching', data: undefined },
94 ])
95 expect(results[3]).toMatchObject([
96 { status: 'success', data: 1 },
97 { status: 'pending', fetchStatus: 'fetching', data: undefined },
98 ])
99 expect(results[4]).toMatchObject([
100 { status: 'success', data: 1 },
101 { status: 'success', data: 2 },
102 ])
103 expect(results[5]).toMatchObject([
104 { status: 'success', data: 1 },
105 { status: 'success', data: 3 },
106 ])
107 })
108β
109 it('should return current observers via getObservers', async () => {
110 const key1 = queryKey()
111 const key2 = queryKey()
112 const queryFn1 = vi.fn().mockReturnValue(1)
113 const queryFn2 = vi.fn().mockReturnValue(2)
114 const observer = new QueriesObserver(queryClient, [
115 { queryKey: key1, queryFn: queryFn1 },
116 { queryKey: key2, queryFn: queryFn2 },
117 ])
118 const unsubscribe = observer.subscribe(() => undefined)
119β
120 await vi.advanceTimersByTimeAsync(0)
121β
122 const observers = observer.getObservers()
123β
124 expect(observers).toHaveLength(2)
125 expect(observers[0]).toBeInstanceOf(QueryObserver)
126 expect(observers[1]).toBeInstanceOf(QueryObserver)
127β
128 unsubscribe()
129 })
130β
131 it('should update when a query is removed', async () => {
132 const key1 = queryKey()
133 const key2 = queryKey()
134 const queryFn1 = vi.fn().mockReturnValue(1)
135 const queryFn2 = vi.fn().mockReturnValue(2)
136 const observer = new QueriesObserver(queryClient, [
137 { queryKey: key1, queryFn: queryFn1 },
138 { queryKey: key2, queryFn: queryFn2 },
139 ])
140 const results: Array<Array<QueryObserverResult>> = []
141 results.push(observer.getCurrentResult())
142 const unsubscribe = observer.subscribe((result) => {
143 results.push(result)
144 })
145β
146 await vi.advanceTimersByTimeAsync(0)
147 observer.setQueries([{ queryKey: key2, queryFn: queryFn2 }])
148β
149 const queryCache = queryClient.getQueryCache()
150β
151 expect(queryCache.find({ queryKey: key1, type: 'active' })).toBeUndefined()
152 expect(
153 queryCache.find({ queryKey: key2, type: 'active' })?.queryKey,
154 ).toEqual(key2)
155 unsubscribe()
156 expect(queryCache.find({ queryKey: key1, type: 'active' })).toBeUndefined()
157 expect(queryCache.find({ queryKey: key2, type: 'active' })).toBeUndefined()
158 expect(results.length).toBe(6)
159 expect(results[0]).toMatchObject([
160 { status: 'pending', fetchStatus: 'idle', data: undefined },
161 { status: 'pending', fetchStatus: 'idle', data: undefined },
162 ])
163 expect(results[1]).toMatchObject([
164 { status: 'pending', fetchStatus: 'fetching', data: undefined },
165 { status: 'pending', fetchStatus: 'idle', data: undefined },
166 ])
167 expect(results[2]).toMatchObject([
168 { status: 'pending', fetchStatus: 'fetching', data: undefined },
169 { status: 'pending', fetchStatus: 'fetching', data: undefined },
170 ])
171 expect(results[3]).toMatchObject([
172 { status: 'success', data: 1 },
173 { status: 'pending', fetchStatus: 'fetching', data: undefined },
174 ])
175 expect(results[4]).toMatchObject([
176 { status: 'success', data: 1 },
177 { status: 'success', data: 2 },
178 ])
179 expect(results[5]).toMatchObject([{ status: 'success', data: 2 }])
180 })
181β
182 it('should update when a query changed position', async () => {
183 const key1 = queryKey()
184 const key2 = queryKey()
185 const queryFn1 = vi.fn().mockReturnValue(1)
186 const queryFn2 = vi.fn().mockReturnValue(2)
187 const observer = new QueriesObserver(queryClient, [
188 { queryKey: key1, queryFn: queryFn1 },
189 { queryKey: key2, queryFn: queryFn2 },
190 ])
191 const results: Array<Array<QueryObserverResult>> = []
192 results.push(observer.getCurrentResult())
193 const unsubscribe = observer.subscribe((result) => {
194 results.push(result)
195 })
196β
197 await vi.advanceTimersByTimeAsync(0)
198 observer.setQueries([
199 { queryKey: key2, queryFn: queryFn2 },
200 { queryKey: key1, queryFn: queryFn1 },
201 ])
202β
203 unsubscribe()
204β
205 expect(results.length).toBe(6)
206 expect(results[0]).toMatchObject([
207 { status: 'pending', fetchStatus: 'idle', data: undefined },
208 { status: 'pending', fetchStatus: 'idle', data: undefined },
209 ])
210 expect(results[1]).toMatchObject([
211 { status: 'pending', fetchStatus: 'fetching', data: undefined },
212 { status: 'pending', fetchStatus: 'idle', data: undefined },
213 ])
214 expect(results[2]).toMatchObject([
215 { status: 'pending', fetchStatus: 'fetching', data: undefined },
216 { status: 'pending', fetchStatus: 'fetching', data: undefined },
217 ])
218 expect(results[3]).toMatchObject([
219 { status: 'success', data: 1 },
220 { status: 'pending', fetchStatus: 'fetching', data: undefined },
221 ])
222 expect(results[4]).toMatchObject([
223 { status: 'success', data: 1 },
224 { status: 'success', data: 2 },
225 ])
226 expect(results[5]).toMatchObject([
227 { status: 'success', data: 2 },
228 { status: 'success', data: 1 },
229 ])
230 })
231β
232 it('should not update when nothing has changed', async () => {
233 const key1 = queryKey()
234 const key2 = queryKey()
235 const queryFn1 = vi.fn().mockReturnValue(1)
236 const queryFn2 = vi.fn().mockReturnValue(2)
237 const observer = new QueriesObserver(queryClient, [
238 { queryKey: key1, queryFn: queryFn1 },
239 { queryKey: key2, queryFn: queryFn2 },
240 ])
241 const results: Array<Array<QueryObserverResult>> = []
242 results.push(observer.getCurrentResult())
243 const unsubscribe = observer.subscribe((result) => {
244 results.push(result)
245 })
246β
247 await vi.advanceTimersByTimeAsync(0)
248 observer.setQueries([
249 { queryKey: key1, queryFn: queryFn1 },
250 { queryKey: key2, queryFn: queryFn2 },
251 ])
252β
253 unsubscribe()
254β
255 expect(results.length).toBe(5)
256 expect(results[0]).toMatchObject([
257 { status: 'pending', fetchStatus: 'idle', data: undefined },
258 { status: 'pending', fetchStatus: 'idle', data: undefined },
259 ])
260 expect(results[1]).toMatchObject([
261 { status: 'pending', fetchStatus: 'fetching', data: undefined },
262 { status: 'pending', fetchStatus: 'idle', data: undefined },
263 ])
264 expect(results[2]).toMatchObject([
265 { status: 'pending', fetchStatus: 'fetching', data: undefined },
266 { status: 'pending', fetchStatus: 'fetching', data: undefined },
267 ])
268 expect(results[3]).toMatchObject([
269 { status: 'success', data: 1 },
270 { status: 'pending', fetchStatus: 'fetching', data: undefined },
271 ])
272 expect(results[4]).toMatchObject([
273 { status: 'success', data: 1 },
274 { status: 'success', data: 2 },
275 ])
276 })
277β
278 it('should trigger all fetches when subscribed', () => {
279 const key1 = queryKey()
280 const key2 = queryKey()
281 const queryFn1 = vi.fn().mockReturnValue(1)
282 const queryFn2 = vi.fn().mockReturnValue(2)
283 const observer = new QueriesObserver(queryClient, [
284 { queryKey: key1, queryFn: queryFn1 },
285 { queryKey: key2, queryFn: queryFn2 },
286 ])
287β
288 const unsubscribe = observer.subscribe(() => undefined)
289β
290 unsubscribe()
291β
292 expect(queryFn1).toHaveBeenCalledTimes(1)
293 expect(queryFn2).toHaveBeenCalledTimes(1)
294 })
295β
296 it('should not destroy the observer if there is still a subscription', async () => {
297 const key1 = queryKey()
298 const observer = new QueriesObserver(queryClient, [
299 {
300 queryKey: key1,
301 queryFn: () => sleep(20).then(() => 1),
302 },
303 ])
304β
305 const subscription1Handler = vi.fn()
306 const subscription2Handler = vi.fn()
307β
308 const unsubscribe1 = observer.subscribe(subscription1Handler)
309 const unsubscribe2 = observer.subscribe(subscription2Handler)
310β
311 unsubscribe1()
312β
313 await vi.advanceTimersByTimeAsync(20)
314β
315 // 1 call: pending
316 expect(subscription1Handler).toHaveBeenCalledTimes(1)
317 // 1 call: success
318 expect(subscription2Handler).toHaveBeenCalledTimes(1)
319β
320 // Clean-up
321 unsubscribe2()
322 })
323β
324 it('should handle duplicate query keys in different positions', async () => {
325 const key1 = queryKey()
326 const key2 = queryKey()
327 const queryFn1 = vi.fn().mockReturnValue(1)
328 const queryFn2 = vi.fn().mockReturnValue(2)
329β
330 const observer = new QueriesObserver(queryClient, [
331 { queryKey: key1, queryFn: queryFn1 },
332 { queryKey: key2, queryFn: queryFn2 },
333 { queryKey: key1, queryFn: queryFn1 },
334 ])
335β
336 const results: Array<Array<QueryObserverResult>> = []
337β
338 results.push(
339 observer.getOptimisticResult(
340 [
341 { queryKey: key1, queryFn: queryFn1 },
342 { queryKey: key2, queryFn: queryFn2 },
343 { queryKey: key1, queryFn: queryFn1 },
344 ],
345 undefined,
346 )[0],
347 )
348β
349 const unsubscribe = observer.subscribe((result) => {
350 results.push(result)
351 })
352β
353 await vi.advanceTimersByTimeAsync(0)
354β
355 unsubscribe()
356β
357 expect(results.length).toBe(6)
358 expect(results[0]).toMatchObject([
359 { status: 'pending', fetchStatus: 'idle', data: undefined },
360 { status: 'pending', fetchStatus: 'idle', data: undefined },
361 { status: 'pending', fetchStatus: 'idle', data: undefined },
362 ])
363 expect(results[1]).toMatchObject([
364 { status: 'pending', fetchStatus: 'fetching', data: undefined },
365 { status: 'pending', fetchStatus: 'idle', data: undefined },
366 { status: 'pending', fetchStatus: 'idle', data: undefined },
367 ])
368 expect(results[2]).toMatchObject([
369 { status: 'pending', fetchStatus: 'fetching', data: undefined },
370 { status: 'pending', fetchStatus: 'fetching', data: undefined },
371 { status: 'pending', fetchStatus: 'idle', data: undefined },
372 ])
373 expect(results[3]).toMatchObject([
374 { status: 'success', fetchStatus: 'idle', data: 1 },
375 { status: 'pending', fetchStatus: 'fetching', data: undefined },
376 { status: 'pending', fetchStatus: 'idle', data: undefined },
377 ])
378 expect(results[4]).toMatchObject([
379 { status: 'success', fetchStatus: 'idle', data: 1 },
380 { status: 'pending', fetchStatus: 'fetching', data: undefined },
381 { status: 'success', fetchStatus: 'idle', data: 1 },
382 ])
383 expect(results[5]).toMatchObject([
384 { status: 'success', fetchStatus: 'idle', data: 1 },
385 { status: 'success', fetchStatus: 'idle', data: 2 },
386 { status: 'success', fetchStatus: 'idle', data: 1 },
387 ])
388β
389 // Verify that queryFn1 was only called once despite being used twice
390 expect(queryFn1).toHaveBeenCalledTimes(1)
391 expect(queryFn2).toHaveBeenCalledTimes(1)
392 })
393β
394 it('should notify when results change during early return', async () => {
395 const key1 = queryKey()
396 const key2 = queryKey()
397 const queryFn1 = vi.fn().mockReturnValue(1)
398 const queryFn2 = vi.fn().mockReturnValue(2)
399β
400 queryClient.setQueryData(key1, 1)
401 queryClient.setQueryData(key2, 2)
402β
403 const observer = new QueriesObserver(queryClient, [
404 { queryKey: key1, queryFn: queryFn1 },
405 { queryKey: key2, queryFn: queryFn2 },
406 ])
407β
408 const results: Array<Array<QueryObserverResult>> = []
409 results.push(observer.getCurrentResult())
410β
411 const onUpdate = vi.fn((result: Array<QueryObserverResult>) => {
412 results.push(result)
413 })
414 const unsubscribe = observer.subscribe(onUpdate)
415 const baseline = results.length
416β
417 observer.setQueries([
418 {
419 queryKey: key1,
420 queryFn: queryFn1,
421 select: (d: any) => d + 100,
422 },
423 {
424 queryKey: key2,
425 queryFn: queryFn2,
426 select: (d: any) => d + 100,
427 },
428 ])
429β
430 await vi.advanceTimersByTimeAsync(0)
431β
432 unsubscribe()
433β
434 expect(results.length).toBeGreaterThan(baseline)
435 expect(results[results.length - 1]).toMatchObject([
436 { status: 'success', data: 101 },
437 { status: 'success', data: 102 },
438 ])
439 })
440β
441 it('should update combined result when queries are added with stable combine reference', () => {
442 const combine = vi.fn((results: Array<QueryObserverResult>) => ({
443 count: results.length,
444 results,
445 }))
446β
447 const key1 = queryKey()
448 const key2 = queryKey()
449 const queryFn1 = vi.fn().mockReturnValue(1)
450 const queryFn2 = vi.fn().mockReturnValue(2)
451β
452 const observer = new QueriesObserver<{
453 count: number
454 results: Array<QueryObserverResult>
455 }>(queryClient, [{ queryKey: key1, queryFn: queryFn1 }], { combine })
456β
457 const [initialRaw, getInitialCombined] = observer.getOptimisticResult(
458 [{ queryKey: key1, queryFn: queryFn1 }],
459 combine,
460 )
461 const initialCombined = getInitialCombined(initialRaw)
462β
463 expect(initialCombined.count).toBe(1)
464β
465 const newQueries = [
466 { queryKey: key1, queryFn: queryFn1 },
467 { queryKey: key2, queryFn: queryFn2 },
468 ]
469 const [newRaw, getNewCombined] = observer.getOptimisticResult(
470 newQueries,
471 combine,
472 )
473 const newCombined = getNewCombined(newRaw)
474β
475 expect(newCombined.count).toBe(2)
476 })
477β
478 it('should skip combine notifications while suspense queries have no data', () => {
479 const key = queryKey()
480 const combine = vi.fn((results: Array<QueryObserverResult>) =>
481 results.map((result) => result.data),
482 )
483 const query = {
484 queryKey: key,
485 queryFn: () => sleep(10).then(() => 'data'),
486 staleTime: Infinity,
487 suspense: true,
488 }
489β
490 queryClient.setQueryData(key, 'data')
491β
492 const observer = new QueriesObserver<Array<unknown>>(queryClient, [query], {
493 combine,
494 })
495β
496 const [rawResult, getCombinedResult] = observer.getOptimisticResult(
497 [query],
498 combine,
499 )
500 expect(getCombinedResult(rawResult)).toEqual(['data'])
501 expect(combine).toHaveBeenCalledTimes(1)
502β
503 const unsubscribe = observer.subscribe(() => undefined)
504β
505 void queryClient.resetQueries({ queryKey: key })
506 expect(combine).toHaveBeenCalledTimes(1)
507β
508 unsubscribe()
509 })
510β
511 it('should skip combine notifications after suspense is enabled without structural changes', () => {
512 const key = queryKey()
513 const combine = vi.fn((results: Array<QueryObserverResult>) =>
514 results.map((result) => result.data),
515 )
516 const query = {
517 queryKey: key,
518 queryFn: () => sleep(10).then(() => 'data'),
519 staleTime: Infinity,
520 suspense: false,
521 }
522β
523 queryClient.setQueryData(key, 'data')
524β
525 const observer = new QueriesObserver<Array<unknown>>(queryClient, [query], {
526 combine,
527 })
528β
529 const [rawResult, getCombinedResult] = observer.getOptimisticResult(
530 [query],
531 combine,
532 )
533 expect(getCombinedResult(rawResult)).toEqual(['data'])
534 expect(combine).toHaveBeenCalledTimes(1)
535β
536 const unsubscribe = observer.subscribe(() => undefined)
537β
538 observer.setQueries(
539 [
540 {
541 ...query,
542 suspense: true,
543 },
544 ],
545 { combine },
546 )
547β
548 void queryClient.resetQueries({ queryKey: key })
549 expect(combine).toHaveBeenCalledTimes(1)
550β
551 unsubscribe()
552 })
553β
554 it('should handle queries being removed with stable combine reference', () => {
555 const combine = vi.fn((results: Array<QueryObserverResult>) => ({
556 count: results.length,
557 results,
558 }))
559β
560 const key1 = queryKey()
561 const key2 = queryKey()
562 const queryFn1 = vi.fn().mockReturnValue(1)
563 const queryFn2 = vi.fn().mockReturnValue(2)
564β
565 const observer = new QueriesObserver<{
566 count: number
567 results: Array<QueryObserverResult>
568 }>(
569 queryClient,
570 [
571 { queryKey: key1, queryFn: queryFn1 },
572 { queryKey: key2, queryFn: queryFn2 },
573 ],
574 { combine },
575 )
576β
577 const [initialRaw, getInitialCombined] = observer.getOptimisticResult(
578 [
579 { queryKey: key1, queryFn: queryFn1 },
580 { queryKey: key2, queryFn: queryFn2 },
581 ],
582 combine,
583 )
584 const initialCombined = getInitialCombined(initialRaw)
585β
586 expect(initialCombined.count).toBe(2)
587β
588 const newQueries = [{ queryKey: key1, queryFn: queryFn1 }]
589 const [newRaw, getNewCombined] = observer.getOptimisticResult(
590 newQueries,
591 combine,
592 )
593 const newCombined = getNewCombined(newRaw)
594β
595 expect(newCombined.count).toBe(1)
596 })
597β
598 it('should update combined result when queries are replaced with different ones (same length)', () => {
599 const combine = vi.fn((results: Array<QueryObserverResult>) => ({
600 keys: results.map((r) => r.status),
601 results,
602 }))
603β
604 const key1 = queryKey()
605 const key2 = queryKey()
606 const queryFn1 = vi.fn().mockReturnValue(1)
607 const queryFn2 = vi.fn().mockReturnValue(2)
608β
609 queryClient.setQueryData(key1, 'cached-1')
610β
611 const observer = new QueriesObserver<{
612 keys: Array<string>
613 results: Array<QueryObserverResult>
614 }>(queryClient, [{ queryKey: key1, queryFn: queryFn1 }], { combine })
615β
616 const [initialRaw, getInitialCombined] = observer.getOptimisticResult(
617 [{ queryKey: key1, queryFn: queryFn1 }],
618 combine,
619 )
620 const initialCombined = getInitialCombined(initialRaw)
621β
622 expect(initialCombined.keys).toEqual(['success'])
623β
624 const [newRaw, getNewCombined] = observer.getOptimisticResult(
625 [{ queryKey: key2, queryFn: queryFn2 }],
626 combine,
627 )
628 const newCombined = getNewCombined(newRaw)
629β
630 expect(newCombined.keys).toEqual(['pending'])
631 })
632β
633 it('should recalculate combined result when combine function changes', () => {
634 const combine1 = vi.fn((results: Array<QueryObserverResult>) => ({
635 total: results.length,
636 }))
637 const combine2 = vi.fn((results: Array<QueryObserverResult>) => ({
638 total: results.length * 4,
639 }))
640β
641 const key1 = queryKey()
642 const key2 = queryKey()
643 const queryFn1 = vi.fn().mockReturnValue(1)
644 const queryFn2 = vi.fn().mockReturnValue(2)
645β
646 const queries = [
647 { queryKey: key1, queryFn: queryFn1 },
648 { queryKey: key2, queryFn: queryFn2 },
649 ]
650β
651 const observer = new QueriesObserver<{ total: number }>(
652 queryClient,
653 queries,
654 { combine: combine1 },
655 )
656β
657 const [raw1, getCombined1] = observer.getOptimisticResult(queries, combine1)
658 const combined1 = getCombined1(raw1)
659β
660 const [raw2, getCombined2] = observer.getOptimisticResult(queries, combine2)
661 const combined2 = getCombined2(raw2)
662β
663 expect(combined1.total).toBe(2)
664 expect(combined2.total).toBe(8)
665 })
666β
667 it('should use fallback result when combineResult is called without raw argument', () => {
668 const combine = vi.fn((results: Array<QueryObserverResult>) => ({
669 count: results.length,
670 }))
671β
672 const key = queryKey()
673 const queryFn = vi.fn().mockReturnValue(1)
674β
675 const observer = new QueriesObserver<{ count: number }>(
676 queryClient,
677 [{ queryKey: key, queryFn }],
678 { combine },
679 )
680β
681 const [, getCombined] = observer.getOptimisticResult(
682 [{ queryKey: key, queryFn }],
683 combine,
684 )
685 const combined = getCombined()
686β
687 expect(combined.count).toBe(1)
688 })
689β
690 it('should return observer result directly when notifyOnChangeProps is set', () => {
691 const key = queryKey()
692 const queryFn = vi.fn().mockReturnValue(1)
693β
694 const observer = new QueriesObserver(queryClient, [
695 { queryKey: key, queryFn, notifyOnChangeProps: ['data'] },
696 ])
697β
698 const trackResultSpy = vi.spyOn(QueryObserver.prototype, 'trackResult')
699β
700 const [, , trackResult] = observer.getOptimisticResult(
701 [{ queryKey: key, queryFn, notifyOnChangeProps: ['data'] }],
702 undefined,
703 )
704β
705 const trackedResults = trackResult()
706β
707 expect(trackedResults).toHaveLength(1)
708 // trackResult should NOT be called when notifyOnChangeProps is set
709 expect(trackResultSpy).not.toHaveBeenCalled()
710β
711 trackResultSpy.mockRestore()
712 })
713β
714 it('should return cached combined result when nothing has changed', () => {
715 const combine = vi.fn((results: Array<QueryObserverResult>) => ({
716 count: results.length,
717 }))
718β
719 const key = queryKey()
720 const queryFn = vi.fn().mockReturnValue(1)
721β
722 const queries = [{ queryKey: key, queryFn }]
723β
724 const observer = new QueriesObserver<{ count: number }>(
725 queryClient,
726 queries,
727 { combine },
728 )
729β
730 const [raw1, getCombined1] = observer.getOptimisticResult(queries, combine)
731 const combined1 = getCombined1(raw1)
732β
733 const [raw2, getCombined2] = observer.getOptimisticResult(queries, combine)
734 const combined2 = getCombined2(raw2)
735β
736 // Same combine, same queries β cached result returned
737 expect(combined1).toBe(combined2)
738 })
739β
740 it('should track properties on all observers when trackResult is called', () => {
741 const key1 = queryKey()
742 const key2 = queryKey()
743 const queryFn1 = () => 'data1'
744 const queryFn2 = () => 'data2'
745β
746 const observer = new QueriesObserver(queryClient, [
747 { queryKey: key1, queryFn: queryFn1 },
748 { queryKey: key2, queryFn: queryFn2 },
749 ])
750β
751 const trackPropSpy = vi.spyOn(QueryObserver.prototype, 'trackProp')
752β
753 const [, , trackResult] = observer.getOptimisticResult(
754 [
755 { queryKey: key1, queryFn: queryFn1 },
756 { queryKey: key2, queryFn: queryFn2 },
757 ],
758 undefined,
759 )
760β
761 const trackedResults = trackResult()
762β
763 expect(trackedResults).toHaveLength(2)
764β
765 // Accessing a property on the first result should trigger trackProp on all observers
766 void trackedResults[0]!.status
767β
768 // 1 direct call from the accessed observer's proxy +
769 // 2 synchronized calls from onPropTracked callback (one per observer)
770 expect(trackPropSpy).toHaveBeenCalledWith('status')
771 expect(trackPropSpy).toHaveBeenCalledTimes(3)
772β
773 trackPropSpy.mockRestore()
774 })
775β
776 it('should subscribe to new observers when a query is added while subscribed', async () => {
777 const key1 = queryKey()
778 const key2 = queryKey()
779 const key3 = queryKey()
780 const queryFn1 = vi.fn().mockReturnValue(1)
781 const queryFn2 = vi.fn().mockReturnValue(2)
782 const queryFn3 = vi.fn(() => sleep(10).then(() => 3))
783 const observer = new QueriesObserver(queryClient, [
784 { queryKey: key1, queryFn: queryFn1 },
785 { queryKey: key2, queryFn: queryFn2 },
786 ])
787 const results: Array<Array<QueryObserverResult>> = []
788 const unsubscribe = observer.subscribe((result) => {
789 results.push(result)
790 })
791β
792 await vi.advanceTimersByTimeAsync(0)
793β
794 expect(results[results.length - 1]).toMatchObject([
795 { status: 'success', data: 1 },
796 { status: 'success', data: 2 },
797 ])
798β
799 observer.setQueries([
800 { queryKey: key1, queryFn: queryFn1 },
801 { queryKey: key2, queryFn: queryFn2 },
802 { queryKey: key3, queryFn: queryFn3 },
803 ])
804β
805 await vi.advanceTimersByTimeAsync(10)
806β
807 unsubscribe()
808β
809 expect(results[results.length - 1]).toMatchObject([
810 { status: 'success', data: 1 },
811 { status: 'success', data: 2 },
812 { status: 'success', data: 3 },
813 ])
814 })
815})