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

infinite-query-conformance.test.tsx

406 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// An empty dependency list compiles the query once, at mount.
144function mountWithDependencyList(
145 build: QueryBuild,
146 config: InfiniteQueryConfig = {},
147) {
148 const log: Observations = []
149 return makeHandle(
150 renderHook(() =>
151 useRecorded(useLiveInfiniteQuery(build as any, config as any, []), log),
152 ),
153 log,
154 )
156​
157// React compares query identity on two production paths: the identity derived
158// from the query IR on every render (the 1.0 form), and a deprecated
159// dependency list. The suite runs once per path.
160type IdentityPath = `derived` | `dependency list`
161​
162const mountControllableWith = (path: IdentityPath) =>
163 function mountControllable<P>(
164 build: (q: any, param: P) => any,
165 initial: P,
166 config: InfiniteQueryConfig = {},
167 ) {
168 const log: Observations = []
169 const hook = renderHook(
170 ({ param }: { param: P }) =>
171 useRecorded(
172 path === `derived`
173 ? // The callback captures param, so its IR identity changes with it.
174 useLiveInfiniteQuery((q: any) => build(q, param), config as any)
175 : useLiveInfiniteQuery((q: any) => build(q, param), config as any, [
176 param,
177 ]),
178 log,
179 ),
180 { initialProps: { param: initial } },
181 )
182 const guard = rejectReadsAfterRenderError(hook)
183 const handle = makeHandle(hook, log)
184 return {
185 ...handle,
186 setParamSync(param: P) {
187 guard(() => act(() => hook.rerender({ param })))
188 },
189 }
190 }
191​
192function mountCollection(collection: any, config: InfiniteQueryConfig = {}) {
193 const log: Observations = []
194 return makeHandle(
195 renderHook(() =>
196 useRecorded(useLiveInfiniteQuery(collection, config as any), log),
197 ),
198 log,
199 )
201​
202function mountCollectionControllable(
203 initial: any,
204 config: InfiniteQueryConfig = {},
205) {
206 const log: Observations = []
207 const hook = renderHook(
208 ({ collection }) =>
209 useRecorded(useLiveInfiniteQuery(collection, config as any), log),
210 { initialProps: { collection: initial } },
211 )
212 const guard = rejectReadsAfterRenderError(hook)
213 const handle = makeHandle(hook, log)
214 return {
215 ...handle,
216 replaceCollectionSync(collection: any) {
217 guard(() => act(() => hook.rerender({ collection })))
218 },
219 }
221​
222function mountConfigControllable(
223 build: QueryBuild,
224 initial: InfiniteQueryConfig,
225) {
226 const log: Observations = []
227 const hook = renderHook(
228 ({ config }: { config: InfiniteQueryConfig }) =>
229 useRecorded(useLiveInfiniteQuery(build as any, config as any), log),
230 { initialProps: { config: initial } },
231 )
232 const guard = rejectReadsAfterRenderError(hook)
233 const handle = makeHandle(hook, log)
234 return {
235 ...handle,
236 setConfigSync(config: InfiniteQueryConfig) {
237 guard(() => act(() => hook.rerender({ config })))
238 },
239 }
241​
242function mountInputControllable(
243 collection: any,
244 build: QueryBuild,
245 config: InfiniteQueryConfig = {},
246) {
247 const log: Observations = []
248 const hook = renderHook(
249 ({ kind }: { kind: `collection` | `query` }) =>
250 useRecorded(
251 useLiveInfiniteQuery(
252 kind === `collection` ? collection : build,
253 config as any,
254 [kind],
255 ),
256 log,
257 ),
258 {
259 initialProps: {
260 kind: `collection` as `collection` | `query`,
261 },
262 },
263 )
264 const guard = rejectReadsAfterRenderError(hook)
265 const handle = makeHandle(hook, log)
266 return {
267 ...handle,
268 setInputKindSync(kind: `collection` | `query`) {
269 guard(() => act(() => hook.rerender({ kind })))
270 },
271 }
273​
274// The keyed form: the config names a queryKey chosen per step, or none.
275const mountKeyedControllableWith = (path: IdentityPath) =>
276 function mountKeyedControllable<P>(
277 build: (q: any, param: P) => any,
278 key: (param: P) => ReadonlyArray<unknown> | undefined,
279 initial: P,
280 config: InfiniteQueryConfig = {},
281 ) {
282 const log: Observations = []
283 const hook = renderHook(
284 ({ param }: { param: P }) => {
285 const keyed = { ...config, queryKey: key(param) } as any
286 return useRecorded(
287 path === `derived`
288 ? useLiveInfiniteQuery((q: any) => build(q, param), keyed)
289 : useLiveInfiniteQuery((q: any) => build(q, param), keyed, [param]),
290 log,
291 )
292 },
293 { initialProps: { param: initial } },
294 )
295 const guard = rejectReadsAfterRenderError(hook)
296 const handle = makeHandle(hook, log)
297 return {
298 ...handle,
299 setParamSync(param: P) {
300 guard(() => act(() => hook.rerender({ param })))
301 },
302 }
303 }
304​
305const reactInfiniteDriver: InfiniteQueryDriver = {
306 name: `react`,
307 // Each render re-runs the query input and compares its identity.
308 comparesQueryIdentity: true,
309 gt,
310 eq,
311 makeSource,
312 makeOnDemandSource: (data, delay) =>
313 makeInfiniteOnDemandSource({ createCollection, BTreeIndex }, data, delay),
314 makeLaggingOnDemandSource: (data) =>
315 makeInfiniteOnDemandSource(
316 { createCollection, BTreeIndex },
317 data,
318 undefined,
319 `lagging`,
320 ),
321 makePrecreated,
322 makeWindowController: createLiveQueryWindowController,
323 mount,
324 mountControllable: mountControllableWith(`derived`),
325 mountKeyedControllable: mountKeyedControllableWith(`derived`),
326 mountCollection,
327 mountCollectionControllable,
328 mountConfigControllable,
329 mountInputControllable,
330 knownGaps: [],
332​
333runInfiniteQuerySuite(reactInfiniteDriver, registerInfiniteQueryUnitScenarios)
334runInfiniteQuerySuite(
335 {
336 ...reactInfiniteDriver,
337 name: `react (dependency list)`,
338 mount: mountWithDependencyList,
339 mountControllable: mountControllableWith(`dependency list`),
340 mountKeyedControllable: mountKeyedControllableWith(`dependency list`),
341 },
342 registerInfiniteQueryUnitScenarios,
344​
345it(`publishes query-function pages on the first layout commit after mount and dependency replacement`, async () => {
346 const source = makeSource(
347 Array.from({ length: 10 }, (_, index) => ({
348 id: String(index + 1),
349 rank: index + 1,
350 })),
351 )
352 const commits: Array<{ ranks: Array<number>; status: string }> = []
353 const liveQueryCollections = new Set<{ cleanup: () => Promise<void> }>()
354 const hook = renderHook(
355 ({ minimum }: { minimum: number }) => {
356 const result = useLiveInfiniteQuery(
357 (q) =>
358 q
359 .from({ row: source.collection })
360 .where(({ row }) => gt(row.rank, minimum))
361 .orderBy(({ row }) => row.rank, `desc`),
362 { pageSize: 3 },
363 [minimum],
364 )
365 useLayoutEffect(() => {
366 if (!result.collection) {
367 throw new Error(`Expected an enabled infinite-query collection`)
368 }
369 liveQueryCollections.add(result.collection)
370 commits.push({
371 ranks: result.data.map(({ rank }) => rank),
372 status: result.status,
373 })
374 })
375 return result
376 },
377 { initialProps: { minimum: 0 } },
378 )
379​
380 try {
381 await waitFor(() => expect(hook.result.current.status).toBe(`ready`))
382 // The very first commit already carries data: no empty idle flash precedes
383 // it, matching useLiveQuery for a synchronously loaded source.
384 expect(commits[0]).toEqual({
385 ranks: [10, 9, 8],
386 status: `ready`,
387 })
388 commits.length = 0
389 act(() => hook.rerender({ minimum: 8 }))
390 await waitFor(() =>
391 expect(hook.result.current.data.map(({ rank }) => rank)).toEqual([10, 9]),
392 )
393 // Replacing the dependency builds a fresh eager collection, so its first
394 // commit is ready too — no idle flash on re-query.
395 expect(commits[0]).toEqual({
396 ranks: [10, 9],
397 status: `ready`,
398 })
399 } finally {
400 hook.unmount()
401 await Promise.all(
402 Array.from(liveQueryCollections, (collection) => collection.cleanup()),
403 )
404 await source.collection.cleanup()
405 }
406})