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

useQuery-semantics.test.tsx

593 lines18.5 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 { queryKey, sleep } from '@tanstack/query-test-utils'
11import { QueryCache, QueryClient, 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 = queryKey()
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 = queryKey()
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 = queryKey()
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('surfaces a first-load failure to <Errored>', async () => {
106 const key = queryKey()
107​
108 function Page() {
109 const state = useQuery(() => ({
110 queryKey: key,
111 queryFn: () =>
112 sleep(10).then(() => Promise.reject(new Error('fetch failed'))),
113 retry: false,
114 }))
115 return <span>{state.data}</span>
116 }
117​
118 const rendered = renderWithClient(queryClient, () => (
119 <Errored
120 fallback={(err) => <span>error: {(err() as Error).message}</span>}
121 >
122 <Loading fallback={<span>loading</span>}>
123 <Page />
124 </Loading>
125 </Errored>
126 ))
127​
128 expect(rendered.getByText('loading')).toBeInTheDocument()
129 await vi.advanceTimersByTimeAsync(10)
130 expect(rendered.getByText('error: fetch failed')).toBeInTheDocument()
131 })
132​
133 it('keeps stale data and exposes error state when a refetch fails', async () => {
134 const key = queryKey()
135 let count = 0
136​
137 function Page() {
138 const state = useQuery(() => ({
139 queryKey: key,
140 queryFn: () =>
141 sleep(10).then(() =>
142 ++count === 1
143 ? 'good'
144 : Promise.reject(new Error('refetch failed')),
145 ),
146 retry: false,
147 }))
148 return (
149 <div>
150 <span>{state.data}</span>
151 <span>refetchError: {String(state.isRefetchError)}</span>
152 </div>
153 )
154 }
155​
156 const rendered = renderWithClient(queryClient, () => (
157 <Errored fallback={() => <span>boundary</span>}>
158 <Loading fallback={<span>loading</span>}>
159 <Page />
160 </Loading>
161 </Errored>
162 ))
163​
164 await vi.advanceTimersByTimeAsync(10)
165 expect(rendered.getByText('good')).toBeInTheDocument()
166​
167 void queryClient.invalidateQueries({ queryKey: key })
168 await vi.advanceTimersByTimeAsync(10)
169 // Stale data keeps serving; the failure is state, not a crash.
170 expect(rendered.getByText('good')).toBeInTheDocument()
171 expect(rendered.getByText('refetchError: true')).toBeInTheDocument()
172 expect(rendered.queryByText('boundary')).not.toBeInTheDocument()
173 })
174​
175 it('renders placeholderData immediately without suspending', async () => {
176 const key = queryKey()
177​
178 function Page() {
179 const state = useQuery(() => ({
180 queryKey: key,
181 queryFn: () => sleep(10).then(() => 'real'),
182 placeholderData: 'placeholder',
183 }))
184 return (
185 <div>
186 <span>{state.data}</span>
187 <span>placeholder: {String(state.isPlaceholderData)}</span>
188 </div>
189 )
190 }
191​
192 const rendered = renderWithClient(queryClient, () => (
193 <Loading fallback={<span>loading</span>}>
194 <Page />
195 </Loading>
196 ))
197​
198 expect(rendered.getByText('placeholder')).toBeInTheDocument()
199 expect(rendered.getByText('placeholder: true')).toBeInTheDocument()
200 await vi.advanceTimersByTimeAsync(10)
201 expect(rendered.getByText('real')).toBeInTheDocument()
202 expect(rendered.getByText('placeholder: false')).toBeInTheDocument()
203 })
204​
205 it('renders initialData immediately while the mount refetch runs', async () => {
206 const key = queryKey()
207​
208 function Page() {
209 const state = useQuery(() => ({
210 queryKey: key,
211 queryFn: () => sleep(10).then(() => 'fetched'),
212 initialData: 'initial',
213 staleTime: 0,
214 }))
215 return <span>{state.data}</span>
216 }
217​
218 const rendered = renderWithClient(queryClient, () => (
219 <Loading fallback={<span>loading</span>}>
220 <Page />
221 </Loading>
222 ))
223​
224 expect(rendered.getByText('initial')).toBeInTheDocument()
225 await vi.advanceTimersByTimeAsync(10)
226 expect(rendered.getByText('fetched')).toBeInTheDocument()
227 })
228​
229 it('applies select to the settled value', async () => {
230 const key = queryKey()
231​
232 function Page() {
233 const state = useQuery(() => ({
234 queryKey: key,
235 queryFn: () => sleep(10).then(() => ({ name: 'solid' })),
236 select: (d: { name: string }) => d.name.toUpperCase(),
237 }))
238 return <span>{state.data}</span>
239 }
240​
241 const rendered = renderWithClient(queryClient, () => (
242 <Loading fallback={<span>loading</span>}>
243 <Page />
244 </Loading>
245 ))
246​
247 await vi.advanceTimersByTimeAsync(10)
248 expect(rendered.getByText('SOLID')).toBeInTheDocument()
249 })
250​
251 it('reflects setQueryData writes reactively', async () => {
252 const key = queryKey()
253​
254 function Page() {
255 const state = useQuery(() => ({
256 queryKey: key,
257 queryFn: () => sleep(10).then(() => 'fetched'),
258 }))
259 return <span>{state.data}</span>
260 }
261​
262 const rendered = renderWithClient(queryClient, () => (
263 <Loading fallback={<span>loading</span>}>
264 <Page />
265 </Loading>
266 ))
267​
268 await vi.advanceTimersByTimeAsync(10)
269 expect(rendered.getByText('fetched')).toBeInTheDocument()
270​
271 queryClient.setQueryData(key, 'written')
272 await vi.advanceTimersByTimeAsync(0)
273 expect(rendered.getByText('written')).toBeInTheDocument()
274 })
275​
276 it('suspends a disabled query until it is enabled', async () => {
277 const key = queryKey()
278 const [enabled, setEnabled] = createSignal(false)
279​
280 function Page() {
281 const state = useQuery(() => ({
282 queryKey: key,
283 queryFn: () => sleep(10).then(() => 'ready'),
284 enabled: enabled(),
285 }))
286 return <span>{state.data}</span>
287 }
288​
289 const rendered = renderWithClient(queryClient, () => (
290 <Loading fallback={<span>loading</span>}>
291 <Page />
292 </Loading>
293 ))
294​
295 expect(rendered.getByText('loading')).toBeInTheDocument()
296 await vi.advanceTimersByTimeAsync(20)
297 // Still parked: disabled means nothing is in flight to wait for.
298 expect(rendered.getByText('loading')).toBeInTheDocument()
299​
300 setEnabled(true)
301 await vi.advanceTimersByTimeAsync(10)
302 expect(rendered.getByText('ready')).toBeInTheDocument()
303 })
304​
305 it('exposes background fetch state reactively', async () => {
306 const key = queryKey()
307​
308 function Page() {
309 const state = useQuery(() => ({
310 queryKey: key,
311 queryFn: () => sleep(10).then(() => 'data'),
312 }))
313 return (
314 <div>
315 <span>{state.data}</span>
316 <span>fetching: {String(state.isFetching)}</span>
317 </div>
318 )
319 }
320​
321 const rendered = renderWithClient(queryClient, () => (
322 <Loading fallback={<span>loading</span>}>
323 <Page />
324 </Loading>
325 ))
326​
327 await vi.advanceTimersByTimeAsync(10)
328 expect(rendered.getByText('fetching: false')).toBeInTheDocument()
329​
330 void queryClient.invalidateQueries({ queryKey: key })
331 await vi.advanceTimersByTimeAsync(5)
332 expect(rendered.getByText('fetching: true')).toBeInTheDocument()
333​
334 await vi.advanceTimersByTimeAsync(5)
335 expect(rendered.getByText('fetching: false')).toBeInTheDocument()
336 })
337​
338 it('settles isFetching after a key switch (settle events arrive before the hold commits)', async () => {
339 // Regression: the cache-event subscription filtered by the committed
340 // options hash only. On a key switch the new key's fetch settles while
341 // the hold still serves the old options, so the settle event was dropped
342 // β€” data landed (via the promise) but meta/isFetching stayed stale
343 // forever. The filter now also matches the latest computed hash.
344 const key = queryKey()
345​
346 function Page() {
347 const [id, setId] = createSignal(1)
348 const state = useQuery(() => ({
349 queryKey: [key, id()],
350 queryFn: ({ queryKey: [, k] }) => sleep(10).then(() => `v${k}`),
351 }))
352 return (
353 <div>
354 <button onClick={() => setId(2)}>next</button>
355 <div>data: {state.data}</div>
356 <div>isFetching: {String(state.isFetching)}</div>
357 </div>
358 )
359 }
360​
361 const rendered = renderWithClient(queryClient, () => (
362 <Loading fallback={<span>loading</span>}>
363 <Page />
364 </Loading>
365 ))
366​
367 await vi.advanceTimersByTimeAsync(10)
368 expect(rendered.getByText('data: v1')).toBeInTheDocument()
369 expect(rendered.getByText('isFetching: false')).toBeInTheDocument()
370​
371 fireEvent.click(rendered.getByRole('button', { name: /next/i }))
372 await vi.advanceTimersByTimeAsync(5)
373 // Committed UI held, background fetch observable.
374 expect(rendered.getByText('data: v1')).toBeInTheDocument()
375 expect(rendered.getByText('isFetching: true')).toBeInTheDocument()
376​
377 await vi.advanceTimersByTimeAsync(5)
378 expect(rendered.getByText('data: v2')).toBeInTheDocument()
379 expect(rendered.getByText('isFetching: false')).toBeInTheDocument()
380 })
381​
382 // `data` is a store projection: landings reconcile into the existing
383 // proxy graph (keyed, default 'id') instead of replacing it β€” deep reads
384 // are fine-grained and item identity survives across fetches.
385 describe('data store face', () => {
386 it('tracks deep reads at the leaf β€” unrelated changes do not re-run them', async () => {
387 const key = queryKey()
388 let count = 0
389 const nameRenders: Array<string> = []
390 const doneRenders: Array<string> = []
391​
392 function Page() {
393 const state = useQuery(() => ({
394 queryKey: key,
395 queryFn: () =>
396 sleep(10).then(() => {
397 count++
398 return [
399 { id: '1', name: 'first', done: false },
400 // Only this item's `done` flips on refetch.
401 { id: '2', name: 'second', done: count > 1 },
402 ]
403 }),
404 }))
405 return (
406 <div>
407 <span>
408 {(() => {
409 nameRenders.push(state.data[0]!.name)
410 return state.data[0]!.name
411 })()}
412 </span>
413 <span>
414 done:{' '}
415 {(() => {
416 const v = String(state.data[1]!.done)
417 doneRenders.push(v)
418 return v
419 })()}
420 </span>
421 </div>
422 )
423 }
424​
425 const rendered = renderWithClient(queryClient, () => (
426 <Loading fallback={<span>loading</span>}>
427 <Page />
428 </Loading>
429 ))
430​
431 await vi.advanceTimersByTimeAsync(10)
432 expect(rendered.getByText('first')).toBeInTheDocument()
433 expect(rendered.getByText('done: false')).toBeInTheDocument()
434​
435 void queryClient.refetchQueries({ queryKey: key })
436 await vi.advanceTimersByTimeAsync(10)
437 expect(rendered.getByText('done: true')).toBeInTheDocument()
438​
439 // The leaf that changed re-ran; the untouched leaf did not.
440 expect(doneRenders).toEqual(['false', 'true'])
441 expect(nameRenders).toEqual(['first'])
442 })
443​
444 it('reconciles by a custom key', async () => {
445 const key = queryKey()
446 let count = 0
447 let state!: { data: Array<{ uuid: string; v: number }> }
448​
449 function Page() {
450 state = useQuery(() => ({
451 queryKey: key,
452 reconcile: 'uuid',
453 queryFn: () =>
454 sleep(10).then(() => {
455 count++
456 return count === 1
457 ? [
458 { uuid: 'a', v: 1 },
459 { uuid: 'b', v: 2 },
460 ]
461 : // Reordered: keyed reconciliation must move the proxies,
462 // not rebuild them positionally.
463 [
464 { uuid: 'b', v: 2 },
465 { uuid: 'a', v: 3 },
466 ]
467 }),
468 }))
469 return <span>v: {state.data[0]?.v}</span>
470 }
471​
472 const rendered = renderWithClient(queryClient, () => (
473 <Loading fallback={<span>loading</span>}>
474 <Page />
475 </Loading>
476 ))
477​
478 await vi.advanceTimersByTimeAsync(10)
479 expect(rendered.getByText('v: 1')).toBeInTheDocument()
480 const a = state.data[0]
481 const b = state.data[1]
482​
483 void queryClient.refetchQueries({ queryKey: key })
484 await vi.advanceTimersByTimeAsync(10)
485 expect(rendered.getByText('v: 2')).toBeInTheDocument()
486​
487 expect(state.data[0]).toBe(b)
488 expect(state.data[1]).toBe(a)
489 expect(state.data[1]!.v).toBe(3)
490 })
491​
492 it('serves primitive data through the store face', async () => {
493 const key = queryKey()
494​
495 function Page() {
496 const state = useQuery(() => ({
497 queryKey: key,
498 queryFn: () => sleep(10).then(() => 42),
499 }))
500 return <span>n: {state.data}</span>
501 }
502​
503 const rendered = renderWithClient(queryClient, () => (
504 <Loading fallback={<span>loading</span>}>
505 <Page />
506 </Loading>
507 ))
508​
509 await vi.advanceTimersByTimeAsync(10)
510 expect(rendered.getByText('n: 42')).toBeInTheDocument()
511 })
512 })
513​
514 describe('cache removal', () => {
515 // `removeQueries()` drops entries instead of refetching them, and a
516 // mounted observer must not undo that: the read layer recomputes on the
517 // 'removed' event, and rebuilding the entry there would re-point the
518 // observer and let its mount-fetch policy repopulate the removed key.
519 it('leaves a removed query out of the cache while an observer is mounted', async () => {
520 const key = queryKey()
521 let fetches = 0
522 const queryFn = () =>
523 sleep(10).then(() => (++fetches === 1 ? 'v1' : 'v2'))
524 const events: Array<string> = []
525​
526 function Page() {
527 const state = useQuery(() => ({
528 queryKey: key,
529 queryFn,
530 staleTime: 60_000,
531 }))
532 return <span>{state.data}</span>
533 }
534​
535 const rendered = renderWithClient(queryClient, () => (
536 <Loading fallback={<span>loading</span>}>
537 <Page />
538 </Loading>
539 ))
540​
541 await vi.advanceTimersByTimeAsync(10)
542 expect(rendered.getByText('v1')).toBeInTheDocument()
543​
544 queryCache.subscribe((event) => events.push(event.type))
545 queryClient.removeQueries({ queryKey: key })
546 await vi.advanceTimersByTimeAsync(30)
547​
548 // No 'added' behind the 'removed', so nothing re-created the entry.
549 expect(events).toEqual(['removed'])
550 expect(queryCache.getAll()).toHaveLength(0)
551 expect(queryClient.getQueryData(key)).toBeUndefined()
552 // The removal is not a refetch trigger.
553 expect(fetches).toBe(1)
554 // The mounted reader holds the value it last had, rather than
555 // suspending back into <Loading> over a key that no longer exists.
556 expect(rendered.getByText('v1')).toBeInTheDocument()
557 })
558​
559 it('picks up a real entry written after a removal', async () => {
560 const key = queryKey()
561​
562 function Page() {
563 const state = useQuery(() => ({
564 queryKey: key,
565 queryFn: () => sleep(10).then(() => 'v1'),
566 staleTime: 60_000,
567 }))
568 return <span>{state.data}</span>
569 }
570​
571 const rendered = renderWithClient(queryClient, () => (
572 <Loading fallback={<span>loading</span>}>
573 <Page />
574 </Loading>
575 ))
576​
577 await vi.advanceTimersByTimeAsync(10)
578 expect(rendered.getByText('v1')).toBeInTheDocument()
579​
580 queryClient.removeQueries({ queryKey: key })
581 await vi.advanceTimersByTimeAsync(0)
582 expect(queryCache.getAll()).toHaveLength(0)
583​
584 // The held-over entry must not shadow the cache once it owns the hash
585 // again: a write rebuilds it, and the reader tracks the new instance.
586 queryClient.setQueryData(key, 'v2')
587 await vi.advanceTimersByTimeAsync(0)
588​
589 expect(queryCache.getAll()).toHaveLength(1)
590 expect(rendered.getByText('v2')).toBeInTheDocument()
591 })
592 })
593})