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

infinite-query-conformance.test.tsx

403 lines11.8 KB

1/**
2 * React driver for the shared infinite-query conformance suite.
3 *
4 * `renderHook`, `act`, and the hook result are the only React-specific layer.
5 * Sources and query operators come from this package's module realm. The shared
6 * suite owns the page model and histories; this driver defines when React has
7 * committed enough work for those public observations to be read.
8 */
9import { act, renderHook, waitFor } from '@testing-library/react'
10import { useLayoutEffect } from 'react'
11import { expect, it } from 'vitest'
12import {
13 BTreeIndex,
14 createCollection,
15 createLiveQueryCollection,
16 createLiveQueryWindowController,
17 eq,
18 gt,
19} from '@tanstack/db'
20import { mockSyncCollectionOptions } from '../../db/tests/utils'
21import { runInfiniteQuerySuite } from '../../db/tests/conformance/infinite-suite-oracle'
22import { registerInfiniteQueryUnitScenarios } from '../../db/tests/conformance/infinite-suite-cases'
23import { makeInfiniteOnDemandSource } from '../../db/tests/conformance/infinite-on-demand'
24import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
25import { rejectReadsAfterRenderError } from './rejected-binding'
26import type { RenderHookResult } from '@testing-library/react'
27import type {
28 InfiniteQueryConfig,
29 InfiniteQueryDriver,
30 InfiniteQueryHandle,
31 InfiniteQueryObservation,
32} from '../../db/tests/conformance/infinite-contract'
33import type { QueryBuild } from '../../db/tests/conformance/contract'
34​
35let sourceSequence = 0
36​
37function makeSource<T extends { id: string }>(
38 initialData: ReadonlyArray<T>,
39 collectionId?: string,
40) {
41 const collection = createCollection(
42 mockSyncCollectionOptions<T>({
43 autoIndex: `eager`,
44 id: collectionId ?? `infinite-conformance-react-${sourceSequence++}`,
45 getKey: (row) => row.id,
46 initialData: [...initialData],
47 }),
48 )
49 const write = (type: `insert` | `update` | `delete`, value: T) => {
50 collection.utils.begin()
51 collection.utils.write({ type, value })
52 collection.utils.commit()
53 }
54 return {
55 collection,
56 insert: (row: T) => write(`insert`, row),
57 update: (row: T) => write(`update`, row),
58 remove: (row: T) => write(`delete`, row),
59 }
61​
62function makePrecreated(build: QueryBuild) {
63 return {
64 collection: createLiveQueryCollection({ query: build as any }),
65 }
67​
68type Observations = Array<InfiniteQueryObservation>
69​
70function observe(result: any): InfiniteQueryObservation {
71 return {
72 status: result.status,
73 ids: result.data.map((row: { id: string }) => row.id),
74 pages: result.pages.map((page: Array<{ id: string }>) =>
75 page.map((row) => row.id),
76 ),
77 hasNextPage: result.hasNextPage,
78 }
80​
81// React publishes at each layout commit. renderHook can coalesce a commit
82// before it returns, so only a layout effect sees every published value.
83function useRecorded<T>(result: T, log: Observations): T {
84 useLayoutEffect(() => {
85 log.push(observe(result))
86 })
87 return result
89​
90function makeHandle(
91 hook: RenderHookResult<any, any>,
92 log: Observations,
93): InfiniteQueryHandle {
94 return {
95 current() {
96 const result = hook.result.current
97 return {
98 data: result.data,
99 pages: result.pages,
100 pageParams: result.pageParams,
101 hasNextPage: result.hasNextPage,
102 isFetchingNextPage: result.isFetchingNextPage,
103 isLoadingError: result.isLoadingError,
104 status: result.status,
105 collection: result.collection,
106 }
107 },
108 observations: () => log,
109 fetchNextPage() {
110 let request!: Promise<void>
111 act(() => {
112 request = hook.result.current.fetchNextPage()
113 })
114 return request
115 },
116 async flush() {
117 await act(async () => {
118 await new Promise((resolve) => setTimeout(resolve, 0))
119 })
120 },
121 async apply(fn) {
122 await act(async () => {
123 fn()
124 await Promise.resolve()
125 })
126 },
127 unmount() {
128 hook.unmount()
129 },
130 }
132​
133function mount(build: QueryBuild, config: InfiniteQueryConfig = {}) {
134 const log: Observations = []
135 return makeHandle(
136 renderHook(() =>
137 useRecorded(useLiveInfiniteQuery(build as any, config as any), log),
138 ),
139 log,
140 )
142​
143// Retain this registration for replay coordinates. It uses the current
144// derived-identity API.
145function mountWithDependencyList(
146 build: QueryBuild,
147 config: InfiniteQueryConfig = {},
148) {
149 const log: Observations = []
150 return makeHandle(
151 renderHook(() =>
152 useRecorded(useLiveInfiniteQuery(build as any, config as any), log),
153 ),
154 log,
155 )
157​
158// The legacy dependency-list label preserves receiving registrations and replay
159// coordinates. Both branches now use the current derived-identity API; these
160// labels do not represent separate production paths.
161type IdentityPath = `derived` | `dependency list`
162​
163const mountControllableWith = (path: IdentityPath) =>
164 function mountControllable<P>(
165 build: (q: any, param: P) => any,
166 initial: P,
167 config: InfiniteQueryConfig = {},
168 ) {
169 const log: Observations = []
170 const hook = renderHook(
171 ({ param }: { param: P }) =>
172 useRecorded(
173 path === `derived`
174 ? // The callback captures param, so its IR identity changes with it.
175 useLiveInfiniteQuery((q: any) => build(q, param), config as any)
176 : useLiveInfiniteQuery((q: any) => build(q, param), config as any),
177 log,
178 ),
179 { initialProps: { param: initial } },
180 )
181 const guard = rejectReadsAfterRenderError(hook)
182 const handle = makeHandle(hook, log)
183 return {
184 ...handle,
185 setParamSync(param: P) {
186 guard(() => act(() => hook.rerender({ param })))
187 },
188 }
189 }
190​
191function mountCollection(collection: any, config: InfiniteQueryConfig = {}) {
192 const log: Observations = []
193 return makeHandle(
194 renderHook(() =>
195 useRecorded(useLiveInfiniteQuery(collection, config as any), log),
196 ),
197 log,
198 )
200​
201function mountCollectionControllable(
202 initial: any,
203 config: InfiniteQueryConfig = {},
204) {
205 const log: Observations = []
206 const hook = renderHook(
207 ({ collection }) =>
208 useRecorded(useLiveInfiniteQuery(collection, config as any), log),
209 { initialProps: { collection: initial } },
210 )
211 const guard = rejectReadsAfterRenderError(hook)
212 const handle = makeHandle(hook, log)
213 return {
214 ...handle,
215 replaceCollectionSync(collection: any) {
216 guard(() => act(() => hook.rerender({ collection })))
217 },
218 }
220​
221function mountConfigControllable(
222 build: QueryBuild,
223 initial: InfiniteQueryConfig,
224) {
225 const log: Observations = []
226 const hook = renderHook(
227 ({ config }: { config: InfiniteQueryConfig }) =>
228 useRecorded(useLiveInfiniteQuery(build as any, config as any), log),
229 { initialProps: { config: initial } },
230 )
231 const guard = rejectReadsAfterRenderError(hook)
232 const handle = makeHandle(hook, log)
233 return {
234 ...handle,
235 setConfigSync(config: InfiniteQueryConfig) {
236 guard(() => act(() => hook.rerender({ config })))
237 },
238 }
240​
241function mountInputControllable(
242 collection: any,
243 build: QueryBuild,
244 config: InfiniteQueryConfig = {},
245) {
246 const log: Observations = []
247 const hook = renderHook(
248 ({ kind }: { kind: `collection` | `query` }) =>
249 useRecorded(
250 useLiveInfiniteQuery(kind === `collection` ? collection : build, {
251 ...(config as any),
252 queryKey: [kind],
253 }),
254 log,
255 ),
256 {
257 initialProps: {
258 kind: `collection` as `collection` | `query`,
259 },
260 },
261 )
262 const guard = rejectReadsAfterRenderError(hook)
263 const handle = makeHandle(hook, log)
264 return {
265 ...handle,
266 setInputKindSync(kind: `collection` | `query`) {
267 guard(() => act(() => hook.rerender({ kind })))
268 },
269 }
271​
272// The keyed form: the config names a queryKey chosen per step, or none.
273const mountKeyedControllableWith = (path: IdentityPath) =>
274 function mountKeyedControllable<P>(
275 build: (q: any, param: P) => any,
276 key: (param: P) => ReadonlyArray<unknown> | undefined,
277 initial: P,
278 config: InfiniteQueryConfig = {},
279 ) {
280 const log: Observations = []
281 const hook = renderHook(
282 ({ param }: { param: P }) => {
283 const keyed = { ...config, queryKey: key(param) } as any
284 return useRecorded(
285 path === `derived`
286 ? useLiveInfiniteQuery((q: any) => build(q, param), keyed)
287 : useLiveInfiniteQuery((q: any) => build(q, param), keyed),
288 log,
289 )
290 },
291 { initialProps: { param: initial } },
292 )
293 const guard = rejectReadsAfterRenderError(hook)
294 const handle = makeHandle(hook, log)
295 return {
296 ...handle,
297 setParamSync(param: P) {
298 guard(() => act(() => hook.rerender({ param })))
299 },
300 }
301 }
302​
303const reactInfiniteDriver: InfiniteQueryDriver = {
304 name: `react`,
305 // Each render re-runs the query input and compares its identity.
306 comparesQueryIdentity: true,
307 gt,
308 eq,
309 makeSource,
310 makeOnDemandSource: (data, delay) =>
311 makeInfiniteOnDemandSource({ createCollection, BTreeIndex }, data, delay),
312 makeLaggingOnDemandSource: (data) =>
313 makeInfiniteOnDemandSource(
314 { createCollection, BTreeIndex },
315 data,
316 undefined,
317 `lagging`,
318 ),
319 makePrecreated,
320 makeWindowController: createLiveQueryWindowController,
321 mount,
322 mountControllable: mountControllableWith(`derived`),
323 mountKeyedControllable: mountKeyedControllableWith(`derived`),
324 mountCollection,
325 mountCollectionControllable,
326 mountConfigControllable,
327 mountInputControllable,
328 knownGaps: [],
330​
331runInfiniteQuerySuite(reactInfiniteDriver, registerInfiniteQueryUnitScenarios)
332runInfiniteQuerySuite(
333 {
334 ...reactInfiniteDriver,
335 name: `react (dependency list)`,
336 mount: mountWithDependencyList,
337 mountControllable: mountControllableWith(`dependency list`),
338 mountKeyedControllable: mountKeyedControllableWith(`dependency list`),
339 },
340 registerInfiniteQueryUnitScenarios,
342​
343it(`publishes query-function pages on the first layout commit after mount and queryKey replacement`, async () => {
344 const source = makeSource(
345 Array.from({ length: 10 }, (_, index) => ({
346 id: String(index + 1),
347 rank: index + 1,
348 })),
349 )
350 const commits: Array<{ ranks: Array<number>; status: string }> = []
351 const liveQueryCollections = new Set<{ cleanup: () => Promise<void> }>()
352 const hook = renderHook(
353 ({ minimum }: { minimum: number }) => {
354 const result = useLiveInfiniteQuery(
355 (q) =>
356 q
357 .from({ row: source.collection })
358 .where(({ row }) => gt(row.rank, minimum))
359 .orderBy(({ row }) => row.rank, `desc`),
360 { ...{ pageSize: 3 }, queryKey: [minimum] },
361 )
362 useLayoutEffect(() => {
363 if (!result.collection) {
364 throw new Error(`Expected an enabled infinite-query collection`)
365 }
366 liveQueryCollections.add(result.collection)
367 commits.push({
368 ranks: result.data.map(({ rank }) => rank),
369 status: result.status,
370 })
371 })
372 return result
373 },
374 { initialProps: { minimum: 0 } },
375 )
376​
377 try {
378 await waitFor(() => expect(hook.result.current.status).toBe(`ready`))
379 // The very first commit already carries data: no empty idle flash precedes
380 // it, matching useLiveQuery for a synchronously loaded source.
381 expect(commits[0]).toEqual({
382 ranks: [10, 9, 8],
383 status: `ready`,
384 })
385 commits.length = 0
386 act(() => hook.rerender({ minimum: 8 }))
387 await waitFor(() =>
388 expect(hook.result.current.data.map(({ rank }) => rank)).toEqual([10, 9]),
389 )
390 // Replacing queryKey builds a fresh eager collection, so its first
391 // commit is ready too — no idle flash on re-query.
392 expect(commits[0]).toEqual({
393 ranks: [10, 9],
394 status: `ready`,
395 })
396 } finally {
397 hook.unmount()
398 await Promise.all(
399 Array.from(liveQueryCollections, (collection) => collection.cleanup()),
400 )
401 await source.collection.cleanup()
402 }
403})