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

useQuery-semantics.test.tsx

693 lines21.7 KB

1// The 2.0-native read-layer contract: data is an async computation β€” first
2// loads suspend into <Loading>, settled reads are the value (non-nullable),
3// refetches hold the committed UI until fresh data lands, and errors surface
4// through the graph to <Errored>. These tests pin the semantics the rewrite
5// is built around; the legacy suite pins v5 observer mechanics and is being
6// re-pointed separately.
7import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
8import { fireEvent } from '@solidjs/testing-library'
9import { Errored, Loading, createSignal } from 'solid-js'
10import { createKey, sleep } from '@tanstack/query-test-utils'
11import { QueryCache, QueryClient, experimental_streamedQuery, useQuery } from '..'
12import { renderWithClient } from './utils'
13​
14describe('useQuery 2.0 read semantics', () => {
15 let queryCache: QueryCache
16 let queryClient: QueryClient
17​
18 beforeEach(() => {
19 vi.useFakeTimers()
20 queryCache = new QueryCache()
21 queryClient = new QueryClient({ queryCache })
22 })
23​
24 afterEach(() => {
25 queryClient.clear()
26 vi.useRealTimers()
27 })
28​
29 it('suspends the first load into <Loading> and renders data on settle', async () => {
30 const key = createKey()
31​
32 function Page() {
33 const state = useQuery(() => ({
34 queryKey: key,
35 queryFn: () => sleep(10).then(() => 'test'),
36 }))
37 return <span>{state.data}</span>
38 }
39​
40 const rendered = renderWithClient(queryClient, () => (
41 <Loading fallback={<span>loading</span>}>
42 <Page />
43 </Loading>
44 ))
45​
46 expect(rendered.getByText('loading')).toBeInTheDocument()
47 await vi.advanceTimersByTimeAsync(10)
48 expect(rendered.getByText('test')).toBeInTheDocument()
49 })
50​
51 it('serves settled data without guards', async () => {
52 const key = createKey()
53​
54 function Page() {
55 const state = useQuery(() => ({
56 queryKey: key,
57 queryFn: () => sleep(10).then(() => 'test'),
58 }))
59 // The settled read is TData, not TData | undefined β€” method calls
60 // need no optional chaining once the boundary has resolved.
61 return <span>{state.data.toUpperCase()}</span>
62 }
63​
64 const rendered = renderWithClient(queryClient, () => (
65 <Loading fallback={<span>loading</span>}>
66 <Page />
67 </Loading>
68 ))
69​
70 await vi.advanceTimersByTimeAsync(10)
71 expect(rendered.getByText('TEST')).toBeInTheDocument()
72 })
73​
74 it('holds the committed UI through a refetch and swaps when it lands', async () => {
75 const key = createKey()
76 let count = 0
77​
78 function Page() {
79 const state = useQuery(() => ({
80 queryKey: key,
81 queryFn: () => sleep(10).then(() => `data${++count}`),
82 }))
83 return <span>{state.data}</span>
84 }
85​
86 const rendered = renderWithClient(queryClient, () => (
87 <Loading fallback={<span>loading</span>}>
88 <Page />
89 </Loading>
90 ))
91​
92 await vi.advanceTimersByTimeAsync(10)
93 expect(rendered.getByText('data1')).toBeInTheDocument()
94​
95 void queryClient.invalidateQueries({ queryKey: key })
96 await vi.advanceTimersByTimeAsync(5)
97 // Mid-refetch: previous committed value stays visible β€” no fallback.
98 expect(rendered.getByText('data1')).toBeInTheDocument()
99 expect(rendered.queryByText('loading')).not.toBeInTheDocument()
100​
101 await vi.advanceTimersByTimeAsync(5)
102 expect(rendered.getByText('data2')).toBeInTheDocument()
103 })
104​
105 it('shows each streamed chunk as it arrives instead of holding the first one', async () => {
106 const key = createKey()
107​
108 function Page() {
109 const state = useQuery(() => ({
110 queryKey: key,
111 queryFn: experimental_streamedQuery({
112 async *streamFn() {
113 for (const chunk of ['a', 'b', 'c']) {
114 await sleep(50)
115 yield chunk
116 }
117 },
118 }),
119 }))
120 return <span>{state.data.join(' ')}</span>
121 }
122​
123 const rendered = renderWithClient(queryClient, () => (
124 <Loading fallback={<span>loading</span>}>
125 <Page />
126 </Loading>
127 ))
128​
129 expect(rendered.getByText('loading')).toBeInTheDocument()
130 await vi.advanceTimersByTimeAsync(50)
131 expect(rendered.getByText('a')).toBeInTheDocument()
132 await vi.advanceTimersByTimeAsync(50)
133 expect(rendered.getByText('a b')).toBeInTheDocument()
134 await vi.advanceTimersByTimeAsync(50)
135 expect(rendered.getByText('a b c')).toBeInTheDocument()
136 expect(queryClient.getQueryData(key)).toStrictEqual(['a', 'b', 'c'])
137 })
138​
139 it('shows setQueryData writes made during a refetch instead of holding the old value', async () => {
140 const key = createKey()
141 let count = 0
142​
143 function Page() {
144 const state = useQuery(() => ({
145 queryKey: key,
146 queryFn: () => sleep(50).then(() => `data${++count}`),
147 }))
148 return <span>{state.data}</span>
149 }
150​
151 const rendered = renderWithClient(queryClient, () => (
152 <Loading fallback={<span>loading</span>}>
153 <Page />
154 </Loading>
155 ))
156​
157 await vi.advanceTimersByTimeAsync(50)
158 expect(rendered.getByText('data1')).toBeInTheDocument()
159​
160 void queryClient.invalidateQueries({ queryKey: key })
161 await vi.advanceTimersByTimeAsync(10)
162 // Mid-refetch, before any cache write: the committed value still holds.
163 expect(rendered.getByText('data1')).toBeInTheDocument()
164​
165 queryClient.setQueryData(key, 'written')
166 await vi.advanceTimersByTimeAsync(0)
167 expect(rendered.getByText('written')).toBeInTheDocument()
168​
169 await vi.advanceTimersByTimeAsync(40)
170 expect(rendered.getByText('data2')).toBeInTheDocument()
171 })
172​
173 it('still holds the committed value through a refetch when select is set', async () => {
174 const key = createKey()
175 let count = 0
176​
177 function Page() {
178 const state = useQuery(() => ({
179 queryKey: key,
180 queryFn: () => sleep(10).then(() => `data${++count}`),
181 select: (d: string) => d.toUpperCase(),
182 }))
183 return <span>{state.data}</span>
184 }
185​
186 const rendered = renderWithClient(queryClient, () => (
187 <Loading fallback={<span>loading</span>}>
188 <Page />
189 </Loading>
190 ))
191​
192 await vi.advanceTimersByTimeAsync(10)
193 expect(rendered.getByText('DATA1')).toBeInTheDocument()
194​
195 void queryClient.invalidateQueries({ queryKey: key })
196 await vi.advanceTimersByTimeAsync(5)
197 // Mid-refetch: previous committed value stays visible β€” no fallback.
198 expect(rendered.getByText('DATA1')).toBeInTheDocument()
199 expect(rendered.queryByText('loading')).not.toBeInTheDocument()
200​
201 await vi.advanceTimersByTimeAsync(5)
202 expect(rendered.getByText('DATA2')).toBeInTheDocument()
203 })
204​
205 it('surfaces a first-load failure to <Errored>', async () => {
206 const key = createKey()
207​
208 function Page() {
209 const state = useQuery(() => ({
210 queryKey: key,
211 queryFn: () =>
212 sleep(10).then(() => Promise.reject(new Error('fetch failed'))),
213 retry: false,
214 }))
215 return <span>{state.data}</span>
216 }
217​
218 const rendered = renderWithClient(queryClient, () => (
219 <Errored
220 fallback={(err) => <span>error: {(err() as Error).message}</span>}
221 >
222 <Loading fallback={<span>loading</span>}>
223 <Page />
224 </Loading>
225 </Errored>
226 ))
227​
228 expect(rendered.getByText('loading')).toBeInTheDocument()
229 await vi.advanceTimersByTimeAsync(10)
230 expect(rendered.getByText('error: fetch failed')).toBeInTheDocument()
231 })
232​
233 it('keeps stale data and exposes error state when a refetch fails', async () => {
234 const key = createKey()
235 let count = 0
236​
237 function Page() {
238 const state = useQuery(() => ({
239 queryKey: key,
240 queryFn: () =>
241 sleep(10).then(() =>
242 ++count === 1
243 ? 'good'
244 : Promise.reject(new Error('refetch failed')),
245 ),
246 retry: false,
247 }))
248 return (
249 <div>
250 <span>{state.data}</span>
251 <span>refetchError: {String(state.isRefetchError)}</span>
252 </div>
253 )
254 }
255​
256 const rendered = renderWithClient(queryClient, () => (
257 <Errored fallback={() => <span>boundary</span>}>
258 <Loading fallback={<span>loading</span>}>
259 <Page />
260 </Loading>
261 </Errored>
262 ))
263​
264 await vi.advanceTimersByTimeAsync(10)
265 expect(rendered.getByText('good')).toBeInTheDocument()
266​
267 void queryClient.invalidateQueries({ queryKey: key })
268 await vi.advanceTimersByTimeAsync(10)
269 // Stale data keeps serving; the failure is state, not a crash.
270 expect(rendered.getByText('good')).toBeInTheDocument()
271 expect(rendered.getByText('refetchError: true')).toBeInTheDocument()
272 expect(rendered.queryByText('boundary')).not.toBeInTheDocument()
273 })
274​
275 it('renders placeholderData immediately without suspending', async () => {
276 const key = createKey()
277​
278 function Page() {
279 const state = useQuery(() => ({
280 queryKey: key,
281 queryFn: () => sleep(10).then(() => 'real'),
282 placeholderData: 'placeholder',
283 }))
284 return (
285 <div>
286 <span>{state.data}</span>
287 <span>placeholder: {String(state.isPlaceholderData)}</span>
288 </div>
289 )
290 }
291​
292 const rendered = renderWithClient(queryClient, () => (
293 <Loading fallback={<span>loading</span>}>
294 <Page />
295 </Loading>
296 ))
297​
298 expect(rendered.getByText('placeholder')).toBeInTheDocument()
299 expect(rendered.getByText('placeholder: true')).toBeInTheDocument()
300 await vi.advanceTimersByTimeAsync(10)
301 expect(rendered.getByText('real')).toBeInTheDocument()
302 expect(rendered.getByText('placeholder: false')).toBeInTheDocument()
303 })
304​
305 it('renders initialData immediately while the mount refetch runs', async () => {
306 const key = createKey()
307​
308 function Page() {
309 const state = useQuery(() => ({
310 queryKey: key,
311 queryFn: () => sleep(10).then(() => 'fetched'),
312 initialData: 'initial',
313 staleTime: 0,
314 }))
315 return <span>{state.data}</span>
316 }
317​
318 const rendered = renderWithClient(queryClient, () => (
319 <Loading fallback={<span>loading</span>}>
320 <Page />
321 </Loading>
322 ))
323​
324 expect(rendered.getByText('initial')).toBeInTheDocument()
325 await vi.advanceTimersByTimeAsync(10)
326 expect(rendered.getByText('fetched')).toBeInTheDocument()
327 })
328​
329 it('applies select to the settled value', async () => {
330 const key = createKey()
331​
332 function Page() {
333 const state = useQuery(() => ({
334 queryKey: key,
335 queryFn: () => sleep(10).then(() => ({ name: 'solid' })),
336 select: (d: { name: string }) => d.name.toUpperCase(),
337 }))
338 return <span>{state.data}</span>
339 }
340​
341 const rendered = renderWithClient(queryClient, () => (
342 <Loading fallback={<span>loading</span>}>
343 <Page />
344 </Loading>
345 ))
346​
347 await vi.advanceTimersByTimeAsync(10)
348 expect(rendered.getByText('SOLID')).toBeInTheDocument()
349 })
350​
351 it('reflects setQueryData writes reactively', async () => {
352 const key = createKey()
353​
354 function Page() {
355 const state = useQuery(() => ({
356 queryKey: key,
357 queryFn: () => sleep(10).then(() => 'fetched'),
358 }))
359 return <span>{state.data}</span>
360 }
361​
362 const rendered = renderWithClient(queryClient, () => (
363 <Loading fallback={<span>loading</span>}>
364 <Page />
365 </Loading>
366 ))
367​
368 await vi.advanceTimersByTimeAsync(10)
369 expect(rendered.getByText('fetched')).toBeInTheDocument()
370​
371 queryClient.setQueryData(key, 'written')
372 await vi.advanceTimersByTimeAsync(0)
373 expect(rendered.getByText('written')).toBeInTheDocument()
374 })
375​
376 it('suspends a disabled query until it is enabled', async () => {
377 const key = createKey()
378 const [enabled, setEnabled] = createSignal(false)
379​
380 function Page() {
381 const state = useQuery(() => ({
382 queryKey: key,
383 queryFn: () => sleep(10).then(() => 'ready'),
384 enabled: enabled(),
385 }))
386 return <span>{state.data}</span>
387 }
388​
389 const rendered = renderWithClient(queryClient, () => (
390 <Loading fallback={<span>loading</span>}>
391 <Page />
392 </Loading>
393 ))
394​
395 expect(rendered.getByText('loading')).toBeInTheDocument()
396 await vi.advanceTimersByTimeAsync(20)
397 // Still parked: disabled means nothing is in flight to wait for.
398 expect(rendered.getByText('loading')).toBeInTheDocument()
399​
400 setEnabled(true)
401 await vi.advanceTimersByTimeAsync(10)
402 expect(rendered.getByText('ready')).toBeInTheDocument()
403 })
404​
405 it('exposes background fetch state reactively', async () => {
406 const key = createKey()
407​
408 function Page() {
409 const state = useQuery(() => ({
410 queryKey: key,
411 queryFn: () => sleep(10).then(() => 'data'),
412 }))
413 return (
414 <div>
415 <span>{state.data}</span>
416 <span>fetching: {String(state.isFetching)}</span>
417 </div>
418 )
419 }
420​
421 const rendered = renderWithClient(queryClient, () => (
422 <Loading fallback={<span>loading</span>}>
423 <Page />
424 </Loading>
425 ))
426​
427 await vi.advanceTimersByTimeAsync(10)
428 expect(rendered.getByText('fetching: false')).toBeInTheDocument()
429​
430 void queryClient.invalidateQueries({ queryKey: key })
431 await vi.advanceTimersByTimeAsync(5)
432 expect(rendered.getByText('fetching: true')).toBeInTheDocument()
433​
434 await vi.advanceTimersByTimeAsync(5)
435 expect(rendered.getByText('fetching: false')).toBeInTheDocument()
436 })
437​
438 it('settles isFetching after a key switch (settle events arrive before the hold commits)', async () => {
439 // Regression: the cache-event subscription filtered by the committed
440 // options hash only. On a key switch the new key's fetch settles while
441 // the hold still serves the old options, so the settle event was dropped
442 // β€” data landed (via the promise) but meta/isFetching stayed stale
443 // forever. The filter now also matches the latest computed hash.
444 const key = createKey()
445​
446 function Page() {
447 const [id, setId] = createSignal(1)
448 const state = useQuery(() => ({
449 queryKey: [key, id()],
450 queryFn: ({ queryKey: [, k] }) => sleep(10).then(() => `v${k}`),
451 }))
452 return (
453 <div>
454 <button onClick={() => setId(2)}>next</button>
455 <div>data: {state.data}</div>
456 <div>isFetching: {String(state.isFetching)}</div>
457 </div>
458 )
459 }
460​
461 const rendered = renderWithClient(queryClient, () => (
462 <Loading fallback={<span>loading</span>}>
463 <Page />
464 </Loading>
465 ))
466​
467 await vi.advanceTimersByTimeAsync(10)
468 expect(rendered.getByText('data: v1')).toBeInTheDocument()
469 expect(rendered.getByText('isFetching: false')).toBeInTheDocument()
470​
471 fireEvent.click(rendered.getByRole('button', { name: /next/i }))
472 await vi.advanceTimersByTimeAsync(5)
473 // Committed UI held, background fetch observable.
474 expect(rendered.getByText('data: v1')).toBeInTheDocument()
475 expect(rendered.getByText('isFetching: true')).toBeInTheDocument()
476​
477 await vi.advanceTimersByTimeAsync(5)
478 expect(rendered.getByText('data: v2')).toBeInTheDocument()
479 expect(rendered.getByText('isFetching: false')).toBeInTheDocument()
480 })
481​
482 // `data` is a store projection: landings reconcile into the existing
483 // proxy graph (keyed, default 'id') instead of replacing it β€” deep reads
484 // are fine-grained and item identity survives across fetches.
485 describe('data store face', () => {
486 it('tracks deep reads at the leaf β€” unrelated changes do not re-run them', async () => {
487 const key = createKey()
488 let count = 0
489 const nameRenders: Array<string> = []
490 const doneRenders: Array<string> = []
491​
492 function Page() {
493 const state = useQuery(() => ({
494 queryKey: key,
495 queryFn: () =>
496 sleep(10).then(() => {
497 count++
498 return [
499 { id: '1', name: 'first', done: false },
500 // Only this item's `done` flips on refetch.
501 { id: '2', name: 'second', done: count > 1 },
502 ]
503 }),
504 }))
505 return (
506 <div>
507 <span>
508 {(() => {
509 nameRenders.push(state.data[0]!.name)
510 return state.data[0]!.name
511 })()}
512 </span>
513 <span>
514 done:{' '}
515 {(() => {
516 const v = String(state.data[1]!.done)
517 doneRenders.push(v)
518 return v
519 })()}
520 </span>
521 </div>
522 )
523 }
524​
525 const rendered = renderWithClient(queryClient, () => (
526 <Loading fallback={<span>loading</span>}>
527 <Page />
528 </Loading>
529 ))
530​
531 await vi.advanceTimersByTimeAsync(10)
532 expect(rendered.getByText('first')).toBeInTheDocument()
533 expect(rendered.getByText('done: false')).toBeInTheDocument()
534​
535 void queryClient.refetchQueries({ queryKey: key })
536 await vi.advanceTimersByTimeAsync(10)
537 expect(rendered.getByText('done: true')).toBeInTheDocument()
538​
539 // The leaf that changed re-ran; the untouched leaf did not.
540 expect(doneRenders).toStrictEqual(['false', 'true'])
541 expect(nameRenders).toStrictEqual(['first'])
542 })
543​
544 it('reconciles by a custom key', async () => {
545 const key = createKey()
546 let count = 0
547 let state!: { data: Array<{ uuid: string; v: number }> }
548​
549 function Page() {
550 state = useQuery(() => ({
551 queryKey: key,
552 reconcile: 'uuid',
553 queryFn: () =>
554 sleep(10).then(() => {
555 count++
556 return count === 1
557 ? [
558 { uuid: 'a', v: 1 },
559 { uuid: 'b', v: 2 },
560 ]
561 : // Reordered: keyed reconciliation must move the proxies,
562 // not rebuild them positionally.
563 [
564 { uuid: 'b', v: 2 },
565 { uuid: 'a', v: 3 },
566 ]
567 }),
568 }))
569 return <span>v: {state.data[0]?.v}</span>
570 }
571​
572 const rendered = renderWithClient(queryClient, () => (
573 <Loading fallback={<span>loading</span>}>
574 <Page />
575 </Loading>
576 ))
577​
578 await vi.advanceTimersByTimeAsync(10)
579 expect(rendered.getByText('v: 1')).toBeInTheDocument()
580 const a = state.data[0]
581 const b = state.data[1]
582​
583 void queryClient.refetchQueries({ queryKey: key })
584 await vi.advanceTimersByTimeAsync(10)
585 expect(rendered.getByText('v: 2')).toBeInTheDocument()
586​
587 expect(state.data[0]).toBe(b)
588 expect(state.data[1]).toBe(a)
589 expect(state.data[1]!.v).toBe(3)
590 })
591​
592 it('serves primitive data through the store face', async () => {
593 const key = createKey()
594​
595 function Page() {
596 const state = useQuery(() => ({
597 queryKey: key,
598 queryFn: () => sleep(10).then(() => 42),
599 }))
600 return <span>n: {state.data}</span>
601 }
602​
603 const rendered = renderWithClient(queryClient, () => (
604 <Loading fallback={<span>loading</span>}>
605 <Page />
606 </Loading>
607 ))
608​
609 await vi.advanceTimersByTimeAsync(10)
610 expect(rendered.getByText('n: 42')).toBeInTheDocument()
611 })
612 })
613​
614 describe('cache removal', () => {
615 // `removeQueries()` drops entries instead of refetching them, and a
616 // mounted observer must not undo that: the read layer recomputes on the
617 // 'removed' event, and rebuilding the entry there would re-point the
618 // observer and let its mount-fetch policy repopulate the removed key.
619 it('leaves a removed query out of the cache while an observer is mounted', async () => {
620 const key = createKey()
621 let fetches = 0
622 const queryFn = () =>
623 sleep(10).then(() => (++fetches === 1 ? 'v1' : 'v2'))
624 const events: Array<string> = []
625​
626 function Page() {
627 const state = useQuery(() => ({
628 queryKey: key,
629 queryFn,
630 staleTime: 60_000,
631 }))
632 return <span>{state.data}</span>
633 }
634​
635 const rendered = renderWithClient(queryClient, () => (
636 <Loading fallback={<span>loading</span>}>
637 <Page />
638 </Loading>
639 ))
640​
641 await vi.advanceTimersByTimeAsync(10)
642 expect(rendered.getByText('v1')).toBeInTheDocument()
643​
644 queryCache.subscribe((event) => events.push(event.type))
645 queryClient.removeQueries({ queryKey: key })
646 await vi.advanceTimersByTimeAsync(30)
647​
648 // No 'added' behind the 'removed', so nothing re-created the entry.
649 expect(events).toStrictEqual(['removed'])
650 expect(queryCache.getAll()).toHaveLength(0)
651 expect(queryClient.getQueryData(key)).toBeUndefined()
652 // The removal is not a refetch trigger.
653 expect(fetches).toBe(1)
654 // The mounted reader holds the value it last had, rather than
655 // suspending back into <Loading> over a key that no longer exists.
656 expect(rendered.getByText('v1')).toBeInTheDocument()
657 })
658​
659 it('picks up a real entry written after a removal', async () => {
660 const key = createKey()
661​
662 function Page() {
663 const state = useQuery(() => ({
664 queryKey: key,
665 queryFn: () => sleep(10).then(() => 'v1'),
666 staleTime: 60_000,
667 }))
668 return <span>{state.data}</span>
669 }
670​
671 const rendered = renderWithClient(queryClient, () => (
672 <Loading fallback={<span>loading</span>}>
673 <Page />
674 </Loading>
675 ))
676​
677 await vi.advanceTimersByTimeAsync(10)
678 expect(rendered.getByText('v1')).toBeInTheDocument()
679​
680 queryClient.removeQueries({ queryKey: key })
681 await vi.advanceTimersByTimeAsync(0)
682 expect(queryCache.getAll()).toHaveLength(0)
683​
684 // The held-over entry must not shadow the cache once it owns the hash
685 // again: a write rebuilds it, and the reader tracks the new instance.
686 queryClient.setQueryData(key, 'v2')
687 await vi.advanceTimersByTimeAsync(0)
688​
689 expect(queryCache.getAll()).toHaveLength(1)
690 expect(rendered.getByText('v2')).toBeInTheDocument()
691 })
692 })
693})