Open History to see the last commit
1/**
2 * Parity sweep — the behaviors added/fixed to close the audit gaps: the suspense
3 * clearReset retry loop, render-prop QueryErrorResetBoundary, HydrationBoundary
4 * newer/older/streaming semantics, experimental_prefetchInRender's promise,
5 * useQueries combine, skipToken, fetchNextPage, useSuspenseInfiniteQuery,
6 * usePrefetchInfiniteQuery, useMutationState filters+select, tracked-props
7 * render efficiency, and the isRestoring true→false flip.
8 */
9import { beforeEach, describe, expect, it } from 'vitest'
10import { QueryClient, dehydrate } from '@tanstack/octane-query'
11import { mount, nextPaint } from '../_helpers'
12import {
13 CombineApp,
14 FlipRestoringApp,
15 HydrationApp,
16 InfiniteApp,
17 MutationStateApp,
18 PrefetchInRenderApp,
19 PrefetchInfiniteApp,
20 RenderPropResetApp,
21 SkipTokenApp,
22 SuspenseInfiniteApp,
23 SuspenseRetryApp,
24 TrackedApp,
25 mutationCounter,
26 promiseCapture,
27 renderPropValues,
28 restoreSetter,
29 trackedRenders,
30} from '../_fixtures/parity.tsrx'
31
32let client: QueryClient
33beforeEach(() => {
34 client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
35 client.mount()
36})
37
38async function flush(n = 6) {
39 for (let i = 0; i < n; i++) {
40 await new Promise((r) => setTimeout(r, 0))
41 await nextPaint()
42 }
43}
44
45describe('suspense error retry loop (clearReset)', () => {
46 it('reset → retry → fail AGAIN re-throws to the boundary (no undefined-data fall-through)', async () => {
47 let calls = 0
48 const queryFn = () => {
49 calls++
50 return Promise.reject(new Error('boom-' + calls))
51 }
52 const r = mount(SuspenseRetryApp, { client, queryFn })
53 await flush()
54
55 // First failure reaches the boundary.
56 expect(r.find('#sq-msg').textContent).toBe('boom-1')
57
58 // Reset + retry: the refetch fails again — the boundary must re-show the
59 // error. Before the clearReset fix, isReset() stayed true at replay so the
60 // component fell through and rendered undefined data.
61 ;(r.find('#sq-retry') as HTMLElement).click()
62 await flush()
63
64 expect(calls).toBeGreaterThanOrEqual(2)
65 expect(r.findAll('#sq-data').length).toBe(0)
66 expect(r.find('#sq-msg').textContent).toContain('boom')
67 r.unmount()
68 })
69})
70
71describe('QueryErrorResetBoundary render-prop children', () => {
72 it('invokes function children with the boundary value', async () => {
73 renderPropValues.length = 0
74 const r = mount(RenderPropResetApp, { client })
75 await flush()
76
77 expect(r.find('#rp-child').textContent).toBe('reset:function')
78 const value = renderPropValues[0] as any
79 expect(typeof value.reset).toBe('function')
80 expect(typeof value.isReset).toBe('function')
81 expect(typeof value.clearReset).toBe('function')
82 // The provided context value is the same object handed to children.
83 expect(value.isReset()).toBe(false)
84 value.reset()
85 expect(value.isReset()).toBe(true)
86 r.unmount()
87 })
88})
89
90describe('HydrationBoundary', () => {
91 // Real dehydrate() payload for `key`, with dataUpdatedAt shifted so the
92 // entry is deterministically newer/older than the cache.
93 function dehydratedWith(
94 key: Array<unknown>,
95 data: string,
96 dataUpdatedAt: number,
97 ) {
98 const source = new QueryClient()
99 source.setQueryData(key, data)
100 const state = dehydrate(source) as any
101 state.queries[0].state.dataUpdatedAt = dataUpdatedAt
102 return state
103 }
104
105 it('hydrates NEWER dehydrated data over the cache, leaves NEWER cache data alone', async () => {
106 const key = ['h1']
107 client.setQueryData(key, 'cached')
108 const cachedAt = client.getQueryCache().find({ queryKey: key })!.state
109 .dataUpdatedAt
110
111 // Newer dehydrated entry — wins.
112 const r = mount(HydrationApp, {
113 client,
114 state: dehydratedWith(key, 'newer', cachedAt + 1000),
115 queryKey: key,
116 })
117 await flush()
118 expect(r.find('#hydrated').textContent).toBe('newer')
119 r.unmount()
120
121 // Older dehydrated entry — must NOT clobber.
122 const r2 = mount(HydrationApp, {
123 client,
124 state: dehydratedWith(key, 'older', cachedAt - 1000),
125 queryKey: key,
126 })
127 await flush()
128 expect(r2.find('#hydrated').textContent).toBe('newer')
129 r2.unmount()
130 })
131
132 it('a dehydrated STREAMING entry (pending promise + later dehydratedAt) re-hydrates a settled query', async () => {
133 const key = ['h2']
134 client.setQueryData(key, 'settled')
135
136 // A REAL streaming chunk: dehydrate a source whose query is still
137 // PENDING, with the documented streaming opt-in (shouldDehydrateQuery
138 // including pending) — the payload then carries the in-flight promise +
139 // dehydratedAt. Its dataUpdatedAt is 0 (no data yet), so only upstream's
140 // streaming condition (promise && dehydratedAt > cache.dataUpdatedAt)
141 // applies.
142 const source = new QueryClient()
143 const inFlight = source.prefetchQuery({
144 queryKey: key,
145 queryFn: () =>
146 new Promise<string>((res) => setTimeout(() => res('streamed'), 5)),
147 })
148 const chunk = dehydrate(source, {
149 shouldDehydrateQuery: () => true,
150 }) as any
151 expect(chunk.queries[0].promise).toBeTruthy()
152 chunk.queries[0].dehydratedAt =
153 client.getQueryCache().find({ queryKey: key })!.state.dataUpdatedAt + 1000
154
155 const r = mount(HydrationApp, { client, state: chunk, queryKey: key })
156 await inFlight
157 await flush()
158 expect(r.find('#hydrated').textContent).toBe('streamed')
159 r.unmount()
160 })
161
162 it('round-trips a real dehydrate() payload', async () => {
163 const source = new QueryClient()
164 source.setQueryData(['rt'], 'round-trip')
165 const state = dehydrate(source)
166
167 const r = mount(HydrationApp, { client, state, queryKey: ['rt'] })
168 await flush()
169 expect(r.find('#hydrated').textContent).toBe('round-trip')
170 r.unmount()
171 })
172})
173
174describe('experimental_prefetchInRender', () => {
175 it('result.promise resolves with the data', async () => {
176 promiseCapture.promise = null
177 const queryFn = () =>
178 new Promise<string>((res) => setTimeout(() => res('pir-data'), 5))
179 const r = mount(PrefetchInRenderApp, { client, queryFn })
180
181 expect(promiseCapture.promise).toBeTruthy()
182 await expect(promiseCapture.promise).resolves.toBe('pir-data')
183 await flush()
184 expect(r.find('#pir').textContent).toBe('data:pir-data')
185 r.unmount()
186 })
187})
188
189describe('useQueries combine', () => {
190 it('renders the combined aggregate, not the raw results array', async () => {
191 const r = mount(CombineApp, { client })
192 await flush()
193 expect(r.find('#combined').textContent).toBe('3:true')
194 r.unmount()
195 })
196})
197
198describe('skipToken', () => {
199 it('disables the query — pending status, idle fetchStatus, no fetch', async () => {
200 const r = mount(SkipTokenApp, { client })
201 await flush()
202 expect(r.find('#skip').textContent).toBe('pending:idle')
203 r.unmount()
204 })
205})
206
207describe('useInfiniteQuery fetchNextPage', () => {
208 it('appends pages and reports hasNextPage', async () => {
209 const pageFn = (page: number) => Promise.resolve('p' + page)
210 const r = mount(InfiniteApp, { client, pageFn })
211 await flush()
212 expect(r.find('#pages').textContent).toBe('p0')
213 expect(r.find('#has-next').textContent).toBe('true')
214 ;(r.find('#next') as HTMLElement).click()
215 await flush()
216 expect(r.find('#pages').textContent).toBe('p0,p1')
217 ;(r.find('#next') as HTMLElement).click()
218 await flush()
219 expect(r.find('#pages').textContent).toBe('p0,p1,p2')
220 expect(r.find('#has-next').textContent).toBe('false')
221 r.unmount()
222 })
223})
224
225describe('useSuspenseInfiniteQuery', () => {
226 it('suspends then renders the first page', async () => {
227 const pageFn = (page: number) =>
228 new Promise<string>((res) => setTimeout(() => res('sp' + page), 5))
229 const r = mount(SuspenseInfiniteApp, { client, pageFn })
230 expect(r.findAll('#sinf-loading').length).toBe(1)
231 await flush()
232 expect(r.find('#sinf').textContent).toBe('sp0')
233 r.unmount()
234 })
235})
236
237describe('usePrefetchInfiniteQuery', () => {
238 it('primes the cache with the first page', async () => {
239 const pageFn = (page: number) => Promise.resolve('pf' + page)
240 const r = mount(PrefetchInfiniteApp, { client, pageFn })
241 await flush()
242 const state = client.getQueryState(['pinf']) as any
243 expect(state?.data?.pages).toEqual(['pf0'])
244 r.unmount()
245 })
246})
247
248describe('useMutationState filters + select', () => {
249 it('selects variables of mutations matching the key filter', async () => {
250 mutationCounter.n = 0
251 const mutationFn = (v: string) => Promise.resolve(v)
252 const r = mount(MutationStateApp, { client, mutationFn })
253 await flush()
254 expect(r.find('#vars').textContent).toBe('none')
255 ;(r.find('#mutate') as HTMLElement).click()
256 await flush()
257 expect(r.find('#vars').textContent).toBe('v-1')
258 ;(r.find('#mutate') as HTMLElement).click()
259 await flush()
260 expect(r.find('#vars').textContent).toBe('v-1,v-2')
261 r.unmount()
262 })
263})
264
265describe('tracked properties', () => {
266 it('a data-only reader does NOT re-render on an isFetching-only change', async () => {
267 trackedRenders.count = 0
268 const queryFn = () =>
269 new Promise<string>((res) => setTimeout(() => res('t'), 2))
270 const r = mount(TrackedApp, { client, queryFn })
271 await flush()
272 expect(r.find('#tracked').textContent).toBe('t')
273 const rendersAfterLoad = trackedRenders.count
274
275 // A background refetch resolving to the SAME data flips isFetching
276 // true→false but leaves data untouched — the tracked-props subscription
277 // must not re-render the component for it.
278 await client.refetchQueries({ queryKey: ['tracked'] })
279 await flush()
280 expect(r.find('#tracked').textContent).toBe('t')
281 expect(trackedRenders.count).toBe(rendersAfterLoad)
282 r.unmount()
283 })
284})
285
286describe('isRestoring flip', () => {
287 it('true → false starts the fetch that restore was holding back', async () => {
288 let calls = 0
289 const queryFn = () => {
290 calls++
291 return Promise.resolve('restored')
292 }
293 const r = mount(FlipRestoringApp, { client, queryFn })
294 await flush()
295 expect(calls).toBe(0)
296 expect(r.find('#flip').textContent).toBe('pending')
297
298 restoreSetter.set!(false)
299 await flush()
300 expect(calls).toBeGreaterThan(0)
301 expect(r.find('#flip').textContent).toBe('data:restored')
302 r.unmount()
303 })
304})