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

conformance.test.tsx

324 lines9.1 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 gt,
20 sum,
21} from '@tanstack/db'
22import { expect, it } from 'vitest'
23import {
24 mockSyncCollectionOptions,
25 mockSyncCollectionOptionsNoInitialState,
26} from '../../db/tests/utils'
27import { useLiveQuery } from '../src/useLiveQuery'
28import { runSuite } from '../../db/tests/conformance/suite'
29import { expectResultSurface } from '../../db/tests/conformance/result-laws'
30import type { RenderHookResult } from '@testing-library/react'
31import type {
32 ConformanceResult,
33 ControllableHandle,
34 DeferredSourceHandle,
35 LiveQueryDriver,
36 QueryBuild,
37} from '../../db/tests/conformance/contract'
38​
39let sourceSeq = 0
40​
41function writer<T extends { id: string }>(collection: any) {
42 return (type: `insert` | `update` | `delete`, value: T) => {
43 collection.utils.begin()
44 collection.utils.write({ type, value })
45 collection.utils.commit()
46 }
48​
49function makeSource<T extends { id: string }>(initialData: ReadonlyArray<T>) {
50 const collection = createCollection(
51 mockSyncCollectionOptions<T>({
52 id: `conformance-react-${sourceSeq++}`,
53 getKey: (r) => r.id,
54 initialData: [...initialData],
55 }),
56 )
57 const write = writer<T>(collection)
58 return {
59 collection,
60 insert: (row: T) => write(`insert`, row),
61 update: (row: T) => write(`update`, row),
62 remove: (row: T) => write(`delete`, row),
63 }
65​
66function makeDeferredSource<
67 T extends { id: string },
68>(): DeferredSourceHandle<T> {
69 const collection = createCollection(
70 mockSyncCollectionOptionsNoInitialState<T>({
71 id: `conformance-react-${sourceSeq++}`,
72 getKey: (r) => r.id,
73 }),
74 )
75 // Start sync so the sync fn binds utils and the collection sits in `loading`
76 // (NoInitialState never calls markReady on its own).
77 collection.startSyncImmediate()
78 const write = writer<T>(collection)
79 return {
80 collection,
81 insert: (row) => write(`insert`, row),
82 update: (row) => write(`update`, row),
83 remove: (row) => write(`delete`, row),
84 emit: (rows) => {
85 collection.utils.begin()
86 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
87 collection.utils.commit()
88 },
89 markReady: () => collection.utils.markReady(),
90 }
92​
93function makePrecreated(build: QueryBuild, opts?: { startSync?: boolean }) {
94 const collection = createLiveQueryCollection({
95 query: build as any,
96 startSync: opts?.startSync ?? true,
97 })
98 return { collection }
100​
101function makeErrorSource() {
102 const expectedError = new Error(`conformance: sync failure`)
103 let startup: { returned: true } | { returned: false; error: unknown } = {
104 returned: true,
105 }
106 const collection = createCollection<{ id: string }>({
107 id: `conformance-react-err-${sourceSeq++}`,
108 getKey: (r) => r.id,
109 startSync: false,
110 sync: {
111 sync: () => {
112 throw expectedError
113 },
114 },
115 })
116 // Starting sync throws → engine catches and sets status to `error`.
117 try {
118 collection.startSyncImmediate()
119 } catch (error) {
120 startup = { returned: false, error }
121 }
122 return { collection, expectedError, startup }
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(build: QueryBuild) {
136 const hook = renderHook(() => useLiveQuery({ query: build as any }))
137 return makeHandle(hook)
139​
140function mountDisabled() {
141 // React's disabled convention: the query callback returns null.
142 const hook = renderHook(() => useLiveQuery(() => null as any))
143 return makeHandle(hook)
145​
146function mountControllable<P>(
147 build: (q: any, param: P) => any,
148 initial: P,
149): ControllableHandle<P> {
150 const hook = renderHook(
151 ({ param }: { param: P }) =>
152 // Param goes in the dependency list so the hook recompiles when it changes.
153 useLiveQuery((q: any) => build(q, param), [param]),
154 { initialProps: { param: initial } },
155 )
156 const handle = makeHandle(hook)
157 return {
158 ...handle,
159 async setParam(param: P) {
160 await act(async () => {
161 hook.rerender({ param })
162 })
163 await handle.flush()
164 },
165 }
167​
168function makeHandle(hook: RenderHookResult<any, any>) {
169 return {
170 current(): ConformanceResult {
171 const r: any = hook.result.current
172 return expectResultSurface({
173 data: r?.data,
174 state: r?.state,
175 status: r?.status,
176 isReady: r?.isReady,
177 persistedStatus: r?.persistedStatus,
178 isPersistedReady: r?.isPersistedReady,
179 persistedError: r?.persistedError,
180 isError: r?.isError,
181 // Read react-db's real `isEnabled` field so the suite catches a broken
182 // one (deriving from status would mask it).
183 isEnabled: r?.isEnabled,
184 })
185 },
186 async flush() {
187 await act(async () => {
188 await new Promise((resolve) => setTimeout(resolve, 0))
189 })
190 },
191 async apply(fn: () => void) {
192 await act(async () => {
193 fn()
194 await new Promise((resolve) => setTimeout(resolve, 0))
195 })
196 },
197 unmount() {
198 hook.unmount()
199 },
200 }
202​
203const reactDriver: LiveQueryDriver = {
204 name: `react`,
205 disabledRepresentation: `absent`,
206 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
207 makeSource,
208 makeDeferredSource,
209 makePrecreated,
210 makeErrorSource,
211 mount,
212 mountControllable,
213 mountCollection,
214 mountConfig,
215 mountDisabled,
216 knownGaps: [],
217 features: { serverSnapshot: true, suspense: true, pooledEqFilters: true },
219​
220runSuite(reactDriver)
221it(`publishes a synchronous ordered limit in the first layout commit`, async () => {
222 const source = makeSource([
223 { id: `1`, rank: 1 },
224 { id: `2`, rank: 2 },
225 { id: `3`, rank: 3 },
226 ])
227 const commits: Array<{ ids: Array<string>; status: string }> = []
228 const hook = renderHook(() => {
229 const result = useLiveQuery((q) =>
230 q
231 .from({ row: source.collection })
232 .orderBy(({ row }) => row.rank)
233 .limit(2),
234 )
235 useLayoutEffect(() => {
236 commits.push({
237 ids: result.data.map(({ id }) => id),
238 status: result.status,
239 })
240 })
241 return result
242 })
243​
244 try {
245 expect(commits[0]).toEqual({ ids: [`1`, `2`], status: `ready` })
246 } finally {
247 const liveQueryCollection = hook.result.current.collection
248 hook.unmount()
249 await liveQueryCollection.cleanup()
250 await source.collection.cleanup()
251 }
252})
253​
254it(`publishes a synchronous full-source ordered limit in the first layout commit`, async () => {
255 // A function filter makes the plan load its whole source; that initial load
256 // shares the synchronous readiness cut with an ordinary ordered request.
257 const source = makeSource([
258 { id: `1`, rank: 1 },
259 { id: `2`, rank: 2 },
260 { id: `3`, rank: 3 },
261 ])
262 const commits: Array<{ ids: Array<string>; status: string }> = []
263 const hook = renderHook(() => {
264 const result = useLiveQuery((q) =>
265 q
266 .from({ row: source.collection })
267 .fn.where(({ row }) => row.rank > 0)
268 .orderBy(({ row }) => row.rank)
269 .limit(2),
270 )
271 useLayoutEffect(() => {
272 commits.push({
273 ids: result.data.map(({ id }) => id),
274 status: result.status,
275 })
276 })
277 return result
278 })
279​
280 try {
281 expect(commits[0]).toEqual({ ids: [`1`, `2`], status: `ready` })
282 } finally {
283 const liveQueryCollection = hook.result.current.collection
284 hook.unmount()
285 await liveQueryCollection.cleanup()
286 await source.collection.cleanup()
287 }
288})
289​
290it(`preserves raw result types through the actual driver reader`, () => {
291 const raw: Record<string, unknown> = {
292 data: [{ id: `a`, value: undefined }],
293 state: new Map(),
294 status: `disabled`,
295 isReady: false,
296 isError: false,
297 isEnabled: false,
298 }
299 const hook = renderHook(() => raw)
300 const handle = makeHandle(hook)
301 try {
302 const healthy = handle.current()
303 expect(healthy.data).toBe(raw.data)
304 expect(healthy.state).toBe(raw.state)
305 expect(healthy.isReady).toBe(false)
306 expect(healthy.isError).toBe(false)
307 expect(healthy.isEnabled).toBe(false)
308 for (const key of [`status`, `isReady`, `isError`, `isEnabled`]) {
309 const original = raw[key]
310 delete raw[key]
311 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
312 for (const invalid of key === `status`
313 ? [undefined, 0]
314 : [undefined, 0, ``]) {
315 raw[key] = invalid
316 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
317 }
318 raw[key] = original
319 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
320 }
321 } finally {
322 handle.unmount()
323 }
324})