Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, test, 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 test('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 test('should update when a query updates', 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 results: Array<Array<QueryObserverResult>> = []
51 results.push(observer.getCurrentResult())
52 const unsubscribe = observer.subscribe((result) => {
53 results.push(result)
54 })
55β
56 await vi.advanceTimersByTimeAsync(0)
57 queryClient.setQueryData(key2, 3)
58 unsubscribe()
59β
60 expect(results.length).toBe(6)
61 expect(results[0]).toMatchObject([
62 { status: 'pending', fetchStatus: 'idle', data: undefined },
63 { status: 'pending', fetchStatus: 'idle', data: undefined },
64 ])
65 expect(results[1]).toMatchObject([
66 { status: 'pending', fetchStatus: 'fetching', data: undefined },
67 { status: 'pending', fetchStatus: 'idle', data: undefined },
68 ])
69 expect(results[2]).toMatchObject([
70 { status: 'pending', fetchStatus: 'fetching', data: undefined },
71 { status: 'pending', fetchStatus: 'fetching', data: undefined },
72 ])
73 expect(results[3]).toMatchObject([
74 { status: 'success', data: 1 },
75 { status: 'pending', fetchStatus: 'fetching', data: undefined },
76 ])
77 expect(results[4]).toMatchObject([
78 { status: 'success', data: 1 },
79 { status: 'success', data: 2 },
80 ])
81 expect(results[5]).toMatchObject([
82 { status: 'success', data: 1 },
83 { status: 'success', data: 3 },
84 ])
85 })
86β
87 test('should update when a query is removed', async () => {
88 const key1 = queryKey()
89 const key2 = queryKey()
90 const queryFn1 = vi.fn().mockReturnValue(1)
91 const queryFn2 = vi.fn().mockReturnValue(2)
92 const observer = new QueriesObserver(queryClient, [
93 { queryKey: key1, queryFn: queryFn1 },
94 { queryKey: key2, queryFn: queryFn2 },
95 ])
96 const results: Array<Array<QueryObserverResult>> = []
97 results.push(observer.getCurrentResult())
98 const unsubscribe = observer.subscribe((result) => {
99 results.push(result)
100 })
101β
102 await vi.advanceTimersByTimeAsync(0)
103 observer.setQueries([{ queryKey: key2, queryFn: queryFn2 }])
104β
105 const queryCache = queryClient.getQueryCache()
106β
107 expect(queryCache.find({ queryKey: key1, type: 'active' })).toBeUndefined()
108 expect(queryCache.find({ queryKey: key2, type: 'active' })).toBeDefined()
109 unsubscribe()
110 expect(queryCache.find({ queryKey: key1, type: 'active' })).toBeUndefined()
111 expect(queryCache.find({ queryKey: key2, type: 'active' })).toBeUndefined()
112 expect(results.length).toBe(6)
113 expect(results[0]).toMatchObject([
114 { status: 'pending', fetchStatus: 'idle', data: undefined },
115 { status: 'pending', fetchStatus: 'idle', data: undefined },
116 ])
117 expect(results[1]).toMatchObject([
118 { status: 'pending', fetchStatus: 'fetching', data: undefined },
119 { status: 'pending', fetchStatus: 'idle', data: undefined },
120 ])
121 expect(results[2]).toMatchObject([
122 { status: 'pending', fetchStatus: 'fetching', data: undefined },
123 { status: 'pending', fetchStatus: 'fetching', data: undefined },
124 ])
125 expect(results[3]).toMatchObject([
126 { status: 'success', data: 1 },
127 { status: 'pending', fetchStatus: 'fetching', data: undefined },
128 ])
129 expect(results[4]).toMatchObject([
130 { status: 'success', data: 1 },
131 { status: 'success', data: 2 },
132 ])
133 expect(results[5]).toMatchObject([{ status: 'success', data: 2 }])
134 })
135β
136 test('should update when a query changed position', async () => {
137 const key1 = queryKey()
138 const key2 = queryKey()
139 const queryFn1 = vi.fn().mockReturnValue(1)
140 const queryFn2 = vi.fn().mockReturnValue(2)
141 const observer = new QueriesObserver(queryClient, [
142 { queryKey: key1, queryFn: queryFn1 },
143 { queryKey: key2, queryFn: queryFn2 },
144 ])
145 const results: Array<Array<QueryObserverResult>> = []
146 results.push(observer.getCurrentResult())
147 const unsubscribe = observer.subscribe((result) => {
148 results.push(result)
149 })
150β
151 await vi.advanceTimersByTimeAsync(0)
152 observer.setQueries([
153 { queryKey: key2, queryFn: queryFn2 },
154 { queryKey: key1, queryFn: queryFn1 },
155 ])
156β
157 unsubscribe()
158β
159 expect(results.length).toBe(6)
160 expect(results[0]).toMatchObject([
161 { status: 'pending', fetchStatus: 'idle', data: undefined },
162 { status: 'pending', fetchStatus: 'idle', data: undefined },
163 ])
164 expect(results[1]).toMatchObject([
165 { status: 'pending', fetchStatus: 'fetching', data: undefined },
166 { status: 'pending', fetchStatus: 'idle', data: undefined },
167 ])
168 expect(results[2]).toMatchObject([
169 { status: 'pending', fetchStatus: 'fetching', data: undefined },
170 { status: 'pending', fetchStatus: 'fetching', data: undefined },
171 ])
172 expect(results[3]).toMatchObject([
173 { status: 'success', data: 1 },
174 { status: 'pending', fetchStatus: 'fetching', data: undefined },
175 ])
176 expect(results[4]).toMatchObject([
177 { status: 'success', data: 1 },
178 { status: 'success', data: 2 },
179 ])
180 expect(results[5]).toMatchObject([
181 { status: 'success', data: 2 },
182 { status: 'success', data: 1 },
183 ])
184 })
185β
186 test('should not update when nothing has changed', async () => {
187 const key1 = queryKey()
188 const key2 = queryKey()
189 const queryFn1 = vi.fn().mockReturnValue(1)
190 const queryFn2 = vi.fn().mockReturnValue(2)
191 const observer = new QueriesObserver(queryClient, [
192 { queryKey: key1, queryFn: queryFn1 },
193 { queryKey: key2, queryFn: queryFn2 },
194 ])
195 const results: Array<Array<QueryObserverResult>> = []
196 results.push(observer.getCurrentResult())
197 const unsubscribe = observer.subscribe((result) => {
198 results.push(result)
199 })
200β
201 await vi.advanceTimersByTimeAsync(0)
202 observer.setQueries([
203 { queryKey: key1, queryFn: queryFn1 },
204 { queryKey: key2, queryFn: queryFn2 },
205 ])
206β
207 unsubscribe()
208β
209 expect(results.length).toBe(5)
210 expect(results[0]).toMatchObject([
211 { status: 'pending', fetchStatus: 'idle', data: undefined },
212 { status: 'pending', fetchStatus: 'idle', data: undefined },
213 ])
214 expect(results[1]).toMatchObject([
215 { status: 'pending', fetchStatus: 'fetching', data: undefined },
216 { status: 'pending', fetchStatus: 'idle', data: undefined },
217 ])
218 expect(results[2]).toMatchObject([
219 { status: 'pending', fetchStatus: 'fetching', data: undefined },
220 { status: 'pending', fetchStatus: 'fetching', data: undefined },
221 ])
222 expect(results[3]).toMatchObject([
223 { status: 'success', data: 1 },
224 { status: 'pending', fetchStatus: 'fetching', data: undefined },
225 ])
226 expect(results[4]).toMatchObject([
227 { status: 'success', data: 1 },
228 { status: 'success', data: 2 },
229 ])
230 })
231β
232 test('should trigger all fetches when subscribed', () => {
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β
242 const unsubscribe = observer.subscribe(() => undefined)
243β
244 unsubscribe()
245β
246 expect(queryFn1).toHaveBeenCalledTimes(1)
247 expect(queryFn2).toHaveBeenCalledTimes(1)
248 })
249β
250 test('should not destroy the observer if there is still a subscription', async () => {
251 const key1 = queryKey()
252 const observer = new QueriesObserver(queryClient, [
253 {
254 queryKey: key1,
255 queryFn: async () => {
256 await sleep(20)
257 return 1
258 },
259 },
260 ])
261β
262 const subscription1Handler = vi.fn()
263 const subscription2Handler = vi.fn()
264β
265 const unsubscribe1 = observer.subscribe(subscription1Handler)
266 const unsubscribe2 = observer.subscribe(subscription2Handler)
267β
268 unsubscribe1()
269β
270 await vi.advanceTimersByTimeAsync(20)
271β
272 // 1 call: pending
273 expect(subscription1Handler).toBeCalledTimes(1)
274 // 1 call: success
275 expect(subscription2Handler).toBeCalledTimes(1)
276β
277 // Clean-up
278 unsubscribe2()
279 })
280β
281 test('should handle duplicate query keys in different positions', async () => {
282 const key1 = queryKey()
283 const key2 = queryKey()
284 const queryFn1 = vi.fn().mockReturnValue(1)
285 const queryFn2 = vi.fn().mockReturnValue(2)
286β
287 const observer = new QueriesObserver(queryClient, [
288 { queryKey: key1, queryFn: queryFn1 },
289 { queryKey: key2, queryFn: queryFn2 },
290 { queryKey: key1, queryFn: queryFn1 },
291 ])
292β
293 const results: Array<Array<QueryObserverResult>> = []
294β
295 results.push(
296 observer.getOptimisticResult(
297 [
298 { queryKey: key1, queryFn: queryFn1 },
299 { queryKey: key2, queryFn: queryFn2 },
300 { queryKey: key1, queryFn: queryFn1 },
301 ],
302 undefined,
303 )[0],
304 )
305β
306 const unsubscribe = observer.subscribe((result) => {
307 results.push(result)
308 })
309β
310 await vi.advanceTimersByTimeAsync(0)
311β
312 unsubscribe()
313β
314 expect(results.length).toBe(6)
315 expect(results[0]).toMatchObject([
316 { status: 'pending', fetchStatus: 'idle', data: undefined },
317 { status: 'pending', fetchStatus: 'idle', data: undefined },
318 { status: 'pending', fetchStatus: 'idle', data: undefined },
319 ])
320 expect(results[1]).toMatchObject([
321 { status: 'pending', fetchStatus: 'fetching', data: undefined },
322 { status: 'pending', fetchStatus: 'idle', data: undefined },
323 { status: 'pending', fetchStatus: 'idle', data: undefined },
324 ])
325 expect(results[2]).toMatchObject([
326 { status: 'pending', fetchStatus: 'fetching', data: undefined },
327 { status: 'pending', fetchStatus: 'fetching', data: undefined },
328 { status: 'pending', fetchStatus: 'idle', data: undefined },
329 ])
330 expect(results[3]).toMatchObject([
331 { status: 'success', fetchStatus: 'idle', data: 1 },
332 { status: 'pending', fetchStatus: 'fetching', data: undefined },
333 { status: 'pending', fetchStatus: 'idle', data: undefined },
334 ])
335 expect(results[4]).toMatchObject([
336 { status: 'success', fetchStatus: 'idle', data: 1 },
337 { status: 'pending', fetchStatus: 'fetching', data: undefined },
338 { status: 'success', fetchStatus: 'idle', data: 1 },
339 ])
340 expect(results[5]).toMatchObject([
341 { status: 'success', fetchStatus: 'idle', data: 1 },
342 { status: 'success', fetchStatus: 'idle', data: 2 },
343 { status: 'success', fetchStatus: 'idle', data: 1 },
344 ])
345β
346 // Verify that queryFn1 was only called once despite being used twice
347 expect(queryFn1).toHaveBeenCalledTimes(1)
348 expect(queryFn2).toHaveBeenCalledTimes(1)
349 })
350β
351 test('should notify when results change during early return', async () => {
352 const key1 = queryKey()
353 const key2 = queryKey()
354 const queryFn1 = vi.fn().mockReturnValue(1)
355 const queryFn2 = vi.fn().mockReturnValue(2)
356β
357 queryClient.setQueryData(key1, 1)
358 queryClient.setQueryData(key2, 2)
359β
360 const observer = new QueriesObserver(queryClient, [
361 { queryKey: key1, queryFn: queryFn1 },
362 { queryKey: key2, queryFn: queryFn2 },
363 ])
364β
365 const results: Array<Array<QueryObserverResult>> = []
366 results.push(observer.getCurrentResult())
367β
368 const onUpdate = vi.fn((result: Array<QueryObserverResult>) => {
369 results.push(result)
370 })
371 const unsubscribe = observer.subscribe(onUpdate)
372 const baseline = results.length
373β
374 observer.setQueries([
375 {
376 queryKey: key1,
377 queryFn: queryFn1,
378 select: (d: any) => d + 100,
379 },
380 {
381 queryKey: key2,
382 queryFn: queryFn2,
383 select: (d: any) => d + 100,
384 },
385 ])
386β
387 await vi.advanceTimersByTimeAsync(0)
388β
389 unsubscribe()
390β
391 expect(results.length).toBeGreaterThan(baseline)
392 expect(results[results.length - 1]).toMatchObject([
393 { status: 'success', data: 101 },
394 { status: 'success', data: 102 },
395 ])
396 })
397β
398 test('should update combined result when queries are added with stable combine reference', () => {
399 const combine = vi.fn((results: Array<QueryObserverResult>) => ({
400 count: results.length,
401 results,
402 }))
403β
404 const key1 = queryKey()
405 const key2 = queryKey()
406 const queryFn1 = vi.fn().mockReturnValue(1)
407 const queryFn2 = vi.fn().mockReturnValue(2)
408β
409 const observer = new QueriesObserver<{
410 count: number
411 results: Array<QueryObserverResult>
412 }>(queryClient, [{ queryKey: key1, queryFn: queryFn1 }], { combine })
413β
414 const [initialRaw, getInitialCombined] = observer.getOptimisticResult(
415 [{ queryKey: key1, queryFn: queryFn1 }],
416 combine,
417 )
418 const initialCombined = getInitialCombined(initialRaw)
419β
420 expect(initialCombined.count).toBe(1)
421β
422 const newQueries = [
423 { queryKey: key1, queryFn: queryFn1 },
424 { queryKey: key2, queryFn: queryFn2 },
425 ]
426 const [newRaw, getNewCombined] = observer.getOptimisticResult(
427 newQueries,
428 combine,
429 )
430 const newCombined = getNewCombined(newRaw)
431β
432 expect(newCombined.count).toBe(2)
433 })
434β
435 test('should handle queries being removed with stable combine reference', () => {
436 const combine = vi.fn((results: Array<QueryObserverResult>) => ({
437 count: results.length,
438 results,
439 }))
440β
441 const key1 = queryKey()
442 const key2 = queryKey()
443 const queryFn1 = vi.fn().mockReturnValue(1)
444 const queryFn2 = vi.fn().mockReturnValue(2)
445β
446 const observer = new QueriesObserver<{
447 count: number
448 results: Array<QueryObserverResult>
449 }>(
450 queryClient,
451 [
452 { queryKey: key1, queryFn: queryFn1 },
453 { queryKey: key2, queryFn: queryFn2 },
454 ],
455 { combine },
456 )
457β
458 const [initialRaw, getInitialCombined] = observer.getOptimisticResult(
459 [
460 { queryKey: key1, queryFn: queryFn1 },
461 { queryKey: key2, queryFn: queryFn2 },
462 ],
463 combine,
464 )
465 const initialCombined = getInitialCombined(initialRaw)
466β
467 expect(initialCombined.count).toBe(2)
468β
469 const newQueries = [{ queryKey: key1, queryFn: queryFn1 }]
470 const [newRaw, getNewCombined] = observer.getOptimisticResult(
471 newQueries,
472 combine,
473 )
474 const newCombined = getNewCombined(newRaw)
475β
476 expect(newCombined.count).toBe(1)
477 })
478β
479 test('should update combined result when queries are replaced with different ones (same length)', () => {
480 const combine = vi.fn((results: Array<QueryObserverResult>) => ({
481 keys: results.map((r) => r.status),
482 results,
483 }))
484β
485 const key1 = queryKey()
486 const key2 = queryKey()
487 const queryFn1 = vi.fn().mockReturnValue(1)
488 const queryFn2 = vi.fn().mockReturnValue(2)
489β
490 queryClient.setQueryData(key1, 'cached-1')
491β
492 const observer = new QueriesObserver<{
493 keys: Array<string>
494 results: Array<QueryObserverResult>
495 }>(queryClient, [{ queryKey: key1, queryFn: queryFn1 }], { combine })
496β
497 const [initialRaw, getInitialCombined] = observer.getOptimisticResult(
498 [{ queryKey: key1, queryFn: queryFn1 }],
499 combine,
500 )
501 const initialCombined = getInitialCombined(initialRaw)
502β
503 expect(initialCombined.keys).toEqual(['success'])
504β
505 const [newRaw, getNewCombined] = observer.getOptimisticResult(
506 [{ queryKey: key2, queryFn: queryFn2 }],
507 combine,
508 )
509 const newCombined = getNewCombined(newRaw)
510β
511 expect(newCombined.keys).toEqual(['pending'])
512 })
513β
514 test('should track properties on all observers when trackResult is called', () => {
515 const key1 = queryKey()
516 const key2 = queryKey()
517 const queryFn1 = () => 'data1'
518 const queryFn2 = () => 'data2'
519β
520 const observer = new QueriesObserver(queryClient, [
521 { queryKey: key1, queryFn: queryFn1 },
522 { queryKey: key2, queryFn: queryFn2 },
523 ])
524β
525 const trackPropSpy = vi.spyOn(QueryObserver.prototype, 'trackProp')
526β
527 const [, , trackResult] = observer.getOptimisticResult(
528 [
529 { queryKey: key1, queryFn: queryFn1 },
530 { queryKey: key2, queryFn: queryFn2 },
531 ],
532 undefined,
533 )
534β
535 const trackedResults = trackResult()
536β
537 expect(trackedResults).toHaveLength(2)
538β
539 // Accessing a property on the first result should trigger trackProp on all observers
540 void trackedResults[0]!.status
541β
542 // 1 direct call from the accessed observer's proxy +
543 // 2 synchronized calls from onPropTracked callback (one per observer)
544 expect(trackPropSpy).toHaveBeenCalledWith('status')
545 expect(trackPropSpy).toHaveBeenCalledTimes(3)
546β
547 trackPropSpy.mockRestore()
548 })
549})