Open History to see the last commit
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 {
12 coalesce,
13 count,
14 createCollection,
15 createLiveQueryCollection,
16 createOptimisticAction,
17 eq,
18 gt,
19 sum,
20} from '@tanstack/db'
21import { expect, it } from 'vitest'
22import {
23 mockSyncCollectionOptions,
24 mockSyncCollectionOptionsNoInitialState,
25} from '../../db/tests/utils'
26import { useLiveQuery } from '../src/useLiveQuery'
27import { runSuite } from '../../db/tests/conformance/suite'
28import { expectResultSurface } from '../../db/tests/conformance/result-laws'
29import type { RenderHookResult } from '@testing-library/react'
30import type {
31 ConformanceResult,
32 ControllableHandle,
33 DeferredSourceHandle,
34 LiveQueryDriver,
35 QueryBuild,
36 SourceHandle,
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 }
47}
48
49function makeSource<T extends { id: string }>(
50 initialData: ReadonlyArray<T>,
51): SourceHandle<T> {
52 const collection = createCollection(
53 mockSyncCollectionOptions<T>({
54 id: `conformance-react-${sourceSeq++}`,
55 getKey: (r) => r.id,
56 initialData: [...initialData],
57 }),
58 )
59 const write = writer<T>(collection)
60 return {
61 collection,
62 insert: (row) => write(`insert`, row),
63 update: (row) => write(`update`, row),
64 remove: (row) => write(`delete`, row),
65 }
66}
67
68function makeDeferredSource<
69 T extends { id: string },
70>(): DeferredSourceHandle<T> {
71 const collection = createCollection(
72 mockSyncCollectionOptionsNoInitialState<T>({
73 id: `conformance-react-${sourceSeq++}`,
74 getKey: (r) => r.id,
75 }),
76 )
77 // Start sync so the sync fn binds utils and the collection sits in `loading`
78 // (NoInitialState never calls markReady on its own).
79 collection.startSyncImmediate()
80 const write = writer<T>(collection)
81 return {
82 collection,
83 insert: (row) => write(`insert`, row),
84 update: (row) => write(`update`, row),
85 remove: (row) => write(`delete`, row),
86 emit: (rows) => {
87 collection.utils.begin()
88 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
89 collection.utils.commit()
90 },
91 markReady: () => collection.utils.markReady(),
92 }
93}
94
95function makePrecreated(build: QueryBuild, opts?: { startSync?: boolean }) {
96 const collection = createLiveQueryCollection({
97 query: build as any,
98 startSync: opts?.startSync ?? true,
99 })
100 return { collection }
101}
102
103function makeErrorSource() {
104 const expectedError = new Error(`conformance: sync failure`)
105 let startup: { returned: true } | { returned: false; error: unknown } = {
106 returned: true,
107 }
108 const collection = createCollection<{ id: string }>({
109 id: `conformance-react-err-${sourceSeq++}`,
110 getKey: (r) => r.id,
111 startSync: false,
112 sync: {
113 sync: () => {
114 throw expectedError
115 },
116 },
117 })
118 // Starting sync throws → engine catches and sets status to `error`.
119 try {
120 collection.startSyncImmediate()
121 } catch (error) {
122 startup = { returned: false, error }
123 }
124 return { collection, expectedError, startup }
125}
126
127function mount(build: QueryBuild) {
128 const hook = renderHook(() => useLiveQuery(build as any))
129 return makeHandle(hook)
130}
131
132function mountCollection(collection: any) {
133 const hook = renderHook(() => useLiveQuery(collection))
134 return makeHandle(hook)
135}
136
137function mountConfig(build: QueryBuild) {
138 const hook = renderHook(() => useLiveQuery({ query: build as any }))
139 return makeHandle(hook)
140}
141
142function mountDisabled() {
143 // React's disabled convention: the query callback returns null.
144 const hook = renderHook(() => useLiveQuery(() => null as any))
145 return makeHandle(hook)
146}
147
148function mountControllable<P>(
149 build: (q: any, param: P) => any,
150 initial: P,
151): ControllableHandle<P> {
152 const hook = renderHook(
153 ({ param }: { param: P }) =>
154 // Param goes in the dependency list so the hook recompiles when it changes.
155 useLiveQuery((q: any) => build(q, param), [param]),
156 { initialProps: { param: initial } },
157 )
158 const handle = makeHandle(hook)
159 return {
160 ...handle,
161 async setParam(param: P) {
162 await act(async () => {
163 hook.rerender({ param })
164 })
165 await handle.flush()
166 },
167 }
168}
169
170function makeHandle(hook: RenderHookResult<any, any>) {
171 return {
172 current(): ConformanceResult {
173 const r: any = hook.result.current
174 return expectResultSurface({
175 data: r?.data,
176 state: r?.state,
177 status: r?.status,
178 isReady: r?.isReady,
179 isError: r?.isError,
180 // Read react-db's real `isEnabled` field so the suite catches a broken
181 // one (deriving from status would mask it).
182 isEnabled: r?.isEnabled,
183 })
184 },
185 async flush() {
186 await act(async () => {
187 await new Promise((resolve) => setTimeout(resolve, 0))
188 })
189 },
190 async apply(fn: () => void) {
191 await act(async () => {
192 fn()
193 await new Promise((resolve) => setTimeout(resolve, 0))
194 })
195 },
196 unmount() {
197 hook.unmount()
198 },
199 }
200}
201
202const reactDriver: LiveQueryDriver = {
203 name: `react`,
204 disabledRepresentation: `absent`,
205 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
206 makeSource,
207 makeDeferredSource,
208 makePrecreated,
209 makeErrorSource,
210 mount,
211 mountControllable,
212 mountCollection,
213 mountConfig,
214 mountDisabled,
215 knownGaps: [],
216 features: { serverSnapshot: true, suspense: true },
217}
218
219runSuite(reactDriver)
220it(`preserves raw result types through the actual driver reader`, () => {
221 const raw: Record<string, unknown> = {
222 data: [{ id: `a`, value: undefined }],
223 state: new Map(),
224 status: `disabled`,
225 isReady: false,
226 isError: false,
227 isEnabled: false,
228 }
229 const hook = renderHook(() => raw)
230 const handle = makeHandle(hook)
231 try {
232 const healthy = handle.current()
233 expect(healthy.data).toBe(raw.data)
234 expect(healthy.state).toBe(raw.state)
235 expect(healthy.isReady).toBe(false)
236 expect(healthy.isError).toBe(false)
237 expect(healthy.isEnabled).toBe(false)
238 for (const key of [`status`, `isReady`, `isError`, `isEnabled`]) {
239 const original = raw[key]
240 delete raw[key]
241 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
242 for (const invalid of key === `status`
243 ? [undefined, 0]
244 : [undefined, 0, ``]) {
245 raw[key] = invalid
246 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
247 }
248 raw[key] = original
249 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
250 }
251 } finally {
252 handle.unmount()
253 }
254})