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

conformance.test.tsx

486 lines14.6 KB

1/**
2 * React reference driver for the shared live-query conformance suite.
3 *
4 * Everything realm-sensitive — collection creation and query operators — is
5 * imported here (React package's `@tanstack/db`) and handed to the shared
6 * scenarios, so instances match what this package's `useLiveQuery` expects.
7 *
8 * All registered laws must pass; the driver has no whole-test waivers.
9 */
10import { act, renderHook } from '@testing-library/react'
11import { useLayoutEffect } from 'react'
12import {
13 BTreeIndex,
14 BasicIndex,
15 coalesce,
16 count,
17 createCollection,
18 createLiveQueryCollection,
19 createOptimisticAction,
20 eq,
21 groupKeys,
22 gt,
23 sum,
24} from '@tanstack/db'
25import { expect, it } from 'vitest'
26import {
27 mockSyncCollectionOptions,
28 mockSyncCollectionOptionsNoInitialState,
29} from '../../db/tests/utils'
30import { useLiveQuery } from '../src/useLiveQuery'
31import { runSuite } from '../../db/tests/conformance/suite'
32import { createPublicationLog } from '../../db/tests/conformance/publication-log'
33import { makeLaggingSource } from '../../db/tests/conformance/lagging-source'
34import { makeSyncSource } from '../../db/tests/conformance/sync-source'
35import { makeErrorSource as makeSharedErrorSource } from '../../db/tests/conformance/error-source'
36import { expectResultSurface } from '../../db/tests/conformance/result-laws'
37import { rejectReadsAfterRenderError } from './rejected-binding'
38import type { RenderHookResult } from '@testing-library/react'
39import type { PooledLiveQueries } from '@tanstack/db'
40import type {
41 ConformanceResult,
42 ControllableHandle,
43 DeferredSourceHandle,
44 LiveQueryDriver,
45 QueryBuild,
46} from '../../db/tests/conformance/contract'
47​
48let sourceSeq = 0
49​
50function writer<T extends { id: string }>(collection: any) {
51 return (type: `insert` | `update` | `delete`, value: T) => {
52 collection.utils.begin()
53 collection.utils.write({ type, value })
54 collection.utils.commit()
55 }
57​
58function makeSource<T extends { id: string }>(
59 initialData: ReadonlyArray<T>,
60 collectionId?: string,
61 options?: { rowUpdateMode?: `full` },
62) {
63 const collection = createCollection(
64 mockSyncCollectionOptions<T>({
65 id: collectionId ?? `conformance-react-${sourceSeq++}`,
66 getKey: (r) => r.id,
67 initialData: [...initialData],
68 rowUpdateMode: options?.rowUpdateMode,
69 }),
70 )
71 const write = writer<T>(collection)
72 return {
73 collection,
74 insert: (row: T) => write(`insert`, row),
75 update: (row: T) => write(`update`, row),
76 remove: (row: T) => write(`delete`, row),
77 }
79​
80function makeDeferredSource<
81 T extends { id: string },
82>(): DeferredSourceHandle<T> {
83 const collection = createCollection(
84 mockSyncCollectionOptionsNoInitialState<T>({
85 id: `conformance-react-${sourceSeq++}`,
86 getKey: (r) => r.id,
87 }),
88 )
89 // Start sync so the sync fn binds utils and the collection sits in `loading`
90 // (NoInitialState never calls markReady on its own).
91 collection.startSyncImmediate()
92 const write = writer<T>(collection)
93 return {
94 collection,
95 insert: (row) => write(`insert`, row),
96 update: (row) => write(`update`, row),
97 remove: (row) => write(`delete`, row),
98 emit: (rows) => {
99 collection.utils.begin()
100 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
101 collection.utils.commit()
102 },
103 markReady: () => collection.utils.markReady(),
104 }
106​
107function makePrecreated(
108 build: QueryBuild,
109 opts?: { startSync?: boolean; gcTime?: number },
110) {
111 const collection = createLiveQueryCollection({
112 query: build as any,
113 startSync: opts?.startSync ?? true,
114 gcTime: opts?.gcTime,
115 })
116 return { collection }
118​
119function makeErrorSource(kind: `fail` | `crash`) {
120 return makeSharedErrorSource(
121 createCollection,
122 `conformance-react-err-${sourceSeq++}`,
123 kind,
124 )
126​
127function mount(build: QueryBuild) {
128 const hook = renderHook(() => useLiveQuery(build as any))
129 return makeHandle(hook)
131​
132function mountCollection(collection: any) {
133 const hook = renderHook(() => useLiveQuery(collection))
134 return makeHandle(hook)
136​
137function mountConfig(
138 build: QueryBuild,
139 opts?: Parameters<LiveQueryDriver[`mountConfig`]>[1],
140) {
141 const hook = renderHook(() => useLiveQuery({ query: build as any, ...opts }))
142 return makeHandle(hook)
144​
145// Retain this registration for replay coordinates. It uses the current
146// derived-identity API, which checks identity and source claims on each render.
147function mountWithDependencyList(build: QueryBuild) {
148 const hook = renderHook(() => useLiveQuery(build as any))
149 return makeHandle(hook)
151​
152function mountConfigWithDependencyList(
153 build: QueryBuild,
154 opts?: Parameters<LiveQueryDriver[`mountConfig`]>[1],
155) {
156 const hook = renderHook(() =>
157 useLiveQuery({ query: build as any, ...opts } as any),
158 )
159 return makeHandle(hook)
161​
162function mountDisabled() {
163 // React's disabled convention: the query callback returns null.
164 const hook = renderHook(() => useLiveQuery(() => null as any))
165 return makeHandle(hook)
167​
168// The legacy dependency-list label preserves receiving registrations and replay
169// coordinates. Both branches now use the current derived-identity API; these
170// labels do not represent separate production paths.
171type IdentityPath = `derived` | `dependency list`
172​
173const mountControllableWith = (path: IdentityPath) =>
174 function mountControllable<P>(
175 build: (q: any, param: P) => any,
176 initial: P,
177 opts?: { pool?: PooledLiveQueries },
178 ): ControllableHandle<P> {
179 const published = createPublicationLog()
180 const hook = renderHook(
181 ({ param }: { param: P }) => {
182 const query = (q: any) => build(q, param)
183 // Both retained registrations use the config form for a pooled query.
184 const result =
185 opts?.pool !== undefined
186 ? path === `derived`
187 ? useLiveQuery({ query, pool: opts.pool })
188 : useLiveQuery({ query, pool: opts.pool })
189 : path === `derived`
190 ? // The callback captures param, so its IR identity changes with it.
191 useLiveQuery(query)
192 : useLiveQuery(query)
193 // A layout effect records each committed value.
194 useLayoutEffect(() => {
195 published.record(result.data, result.state)
196 })
197 return result
198 },
199 { initialProps: { param: initial } },
200 )
201 const guard = rejectReadsAfterRenderError(hook)
202 const handle = makeHandle(hook)
203 return {
204 ...handle,
205 publications: published.values,
206 statePublications: published.stateValues,
207 async setParam(param: P) {
208 await guard(() =>
209 act(async () => {
210 hook.rerender({ param })
211 }),
212 )
213 await handle.flush()
214 },
215 }
216 }
217​
218function makeHandle(hook: RenderHookResult<any, any>) {
219 return {
220 collection: () => hook.result.current?.collection ?? null,
221 current(): ConformanceResult {
222 const r: any = hook.result.current
223 return expectResultSurface({
224 data: r?.data,
225 state: r?.state,
226 status: r?.status,
227 isReady: r?.isReady,
228 isLoadingError: r?.isLoadingError,
229 isCrashed: r?.isCrashed,
230 isSyncError: r?.isSyncError,
231 // Read react-db's real `isEnabled` field so the suite catches a broken
232 // one (deriving from status would mask it).
233 isEnabled: r?.isEnabled,
234 health: r?.health,
235 })
236 },
237 async flush() {
238 await act(async () => {
239 await new Promise((resolve) => setTimeout(resolve, 0))
240 })
241 },
242 async apply(fn: () => void) {
243 await act(async () => {
244 fn()
245 await new Promise((resolve) => setTimeout(resolve, 0))
246 })
247 },
248 unmount() {
249 hook.unmount()
250 },
251 }
253​
254// The config-object form with a queryKey chosen per step; an undefined key
255// leaves the hook to derive the identity.
256const mountKeyedControllableWith = (path: IdentityPath) =>
257 function mountKeyedControllable<P>(
258 build: (q: any, param: P) => any,
259 key: (param: P) => ReadonlyArray<unknown> | undefined,
260 initial: P,
261 ): ControllableHandle<P> {
262 const published = createPublicationLog()
263 const hook = renderHook(
264 ({ param }: { param: P }) => {
265 const config = {
266 query: (q: any) => build(q, param),
267 queryKey: key(param),
268 } as any
269 const result =
270 path === `derived` ? useLiveQuery(config) : useLiveQuery(config)
271 useLayoutEffect(() => {
272 published.record(result.data, result.state)
273 })
274 return result
275 },
276 { initialProps: { param: initial } },
277 )
278 const guard = rejectReadsAfterRenderError(hook)
279 const handle = makeHandle(hook)
280 return {
281 ...handle,
282 publications: published.values,
283 statePublications: published.stateValues,
284 async setParam(param: P) {
285 await guard(() =>
286 act(async () => {
287 hook.rerender({ param })
288 }),
289 )
290 await handle.flush()
291 },
292 }
293 }
294​
295const reactDriver: LiveQueryDriver = {
296 name: `react`,
297 // Each render re-runs the query input and compares its identity.
298 comparesQueryIdentity: true,
299 disabledRepresentation: `absent`,
300 ops: { eq, gt, count, sum, coalesce, groupKeys, createOptimisticAction },
301 indexTypes: { basic: BasicIndex, btree: BTreeIndex },
302 makeSource,
303 makeDeferredSource,
304 makeLaggingSource: <T extends { id: string }>() =>
305 makeLaggingSource<T>(
306 createCollection,
307 `conformance-react-lagging-${sourceSeq++}`,
308 ),
309 makeSyncSource: <T extends { id: string }>(data: ReadonlyArray<T>) =>
310 makeSyncSource<T>(
311 createCollection,
312 `conformance-react-health-${sourceSeq++}`,
313 data,
314 ),
315 makePrecreated,
316 makeErrorSource,
317 mount,
318 mountControllable: mountControllableWith(`derived`),
319 mountKeyedControllable: mountKeyedControllableWith(`derived`),
320 mountCollection,
321 mountConfig,
322 mountDisabled,
323 knownGaps: [],
324 features: { serverSnapshot: true, suspense: true, pooledEqFilters: true },
326​
327runSuite(reactDriver)
328runSuite({
329 ...reactDriver,
330 name: `react (dependency list)`,
331 mount: mountWithDependencyList,
332 mountConfig: mountConfigWithDependencyList,
333 mountControllable: mountControllableWith(`dependency list`),
334 mountKeyedControllable: mountKeyedControllableWith(`dependency list`),
335})
336it(`publishes a synchronous ordered limit in the first layout commit`, async () => {
337 const source = makeSource([
338 { id: `1`, rank: 1 },
339 { id: `2`, rank: 2 },
340 { id: `3`, rank: 3 },
341 ])
342 const commits: Array<{ ids: Array<string>; status: string }> = []
343 const hook = renderHook(() => {
344 const result = useLiveQuery((q) =>
345 q
346 .from({ row: source.collection })
347 .orderBy(({ row }) => row.rank)
348 .limit(2),
349 )
350 useLayoutEffect(() => {
351 commits.push({
352 ids: result.data.map(({ id }) => id),
353 status: result.status,
354 })
355 })
356 return result
357 })
358​
359 try {
360 expect(commits[0]).toEqual({ ids: [`1`, `2`], status: `ready` })
361 } finally {
362 const liveQueryCollection = hook.result.current.collection
363 hook.unmount()
364 await liveQueryCollection.cleanup()
365 await source.collection.cleanup()
366 }
367})
368​
369it(`publishes a synchronous full-source ordered limit in the first layout commit`, async () => {
370 // A function filter makes the plan load its whole source; that initial load
371 // shares the synchronous readiness cut with an ordinary ordered request.
372 const source = makeSource([
373 { id: `1`, rank: 1 },
374 { id: `2`, rank: 2 },
375 { id: `3`, rank: 3 },
376 ])
377 const commits: Array<{ ids: Array<string>; status: string }> = []
378 const hook = renderHook(() => {
379 const result = useLiveQuery({
380 queryKey: [`full-source-ordered-limit`],
381 query: (q) =>
382 q
383 .from({ row: source.collection })
384 .fn.where(({ row }) => row.rank > 0)
385 .orderBy(({ row }) => row.rank)
386 .limit(2),
387 })
388 useLayoutEffect(() => {
389 commits.push({
390 ids: result.data.map(({ id }) => id),
391 status: result.status,
392 })
393 })
394 return result
395 })
396​
397 try {
398 expect(commits[0]).toEqual({ ids: [`1`, `2`], status: `ready` })
399 } finally {
400 const liveQueryCollection = hook.result.current.collection
401 hook.unmount()
402 await liveQueryCollection.cleanup()
403 await source.collection.cleanup()
404 }
405})
406​
407it(`publishes a locale-string findOne fallback in the first layout commit`, async () => {
408 // A locale string cannot form a provider cursor. Both acquisitions return
409 // literal true from this eager source, so the first window is ready at the
410 // initial render's layout commit.
411 const source = createCollection(
412 mockSyncCollectionOptions({
413 id: `conformance-react-locale-fallback-${sourceSeq++}`,
414 getKey: (row: { id: string; at: string }) => row.id,
415 initialData: [
416 { id: `1`, at: `2026-10-01` },
417 { id: `2`, at: `2026-10-02` },
418 ],
419 autoIndex: `eager`,
420 defaultStringCollation: { stringSort: `locale` },
421 }),
422 )
423 const commits: Array<{ id: string | undefined; status: string }> = []
424 const hook = renderHook(() => {
425 const result = useLiveQuery((q) =>
426 q
427 .from({ row: source })
428 .orderBy(({ row }) => row.at, `desc`)
429 .findOne(),
430 )
431 useLayoutEffect(() => {
432 commits.push({
433 id: result.data?.id,
434 status: result.status,
435 })
436 })
437 return result
438 })
439​
440 try {
441 expect(commits[0]).toEqual({ id: `2`, status: `ready` })
442 } finally {
443 const liveQueryCollection = hook.result.current.collection
444 hook.unmount()
445 await liveQueryCollection.cleanup()
446 await source.cleanup()
447 }
448})
449​
450it(`preserves raw result types through the actual driver reader`, () => {
451 const raw: Record<string, unknown> = {
452 data: [{ id: `a`, value: undefined }],
453 state: new Map(),
454 status: `disabled`,
455 isReady: false,
456 isLoadingError: false,
457 isCrashed: false,
458 isSyncError: false,
459 isEnabled: false,
460 }
461 const hook = renderHook(() => raw)
462 const handle = makeHandle(hook)
463 try {
464 const healthy = handle.current()
465 expect(healthy.data).toBe(raw.data)
466 expect(healthy.state).toBe(raw.state)
467 expect(healthy.isReady).toBe(false)
468 expect(healthy.isLoadingError).toBe(false)
469 expect(healthy.isEnabled).toBe(false)
470 for (const key of [`status`, `isReady`, `isLoadingError`, `isEnabled`]) {
471 const original = raw[key]
472 delete raw[key]
473 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
474 for (const invalid of key === `status`
475 ? [undefined, 0]
476 : [undefined, 0, ``]) {
477 raw[key] = invalid
478 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
479 }
480 raw[key] = original
481 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
482 }
483 } finally {
484 handle.unmount()
485 }
486})