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

conformance.test.tsx

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