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

conformance.test.tsx

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