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

conformance.test.ts

315 lines8.6 KB

1/**
2 * Angular driver for the shared live-query conformance suite.
3 *
4 * `injectLiveQuery` needs an injection context, so each mount runs inside a
5 * child `EnvironmentInjector` created off TestBed's; `unmount` calls
6 * `injector.destroy()`, firing the `DestroyRef` cleanup. Result signals are read
7 * after settling. Controllable inputs use Angular's reactive `{ params, query }`
8 * form driven by a signal.
9 *
10 * All registered laws must pass; the driver has no whole-test waivers.
11 */
12import { describe, expect, it } from 'vitest'
13import {
14 DestroyRef,
15 EnvironmentInjector,
16 createEnvironmentInjector,
17 inject,
18 runInInjectionContext,
19 signal,
20} from '@angular/core'
21import { TestBed } from '@angular/core/testing'
22import {
23 coalesce,
24 count,
25 createCollection,
26 createLiveQueryCollection,
27 createOptimisticAction,
28 eq,
29 gt,
30 sum,
31} from '@tanstack/db'
32import {
33 mockSyncCollectionOptions,
34 mockSyncCollectionOptionsNoInitialState,
35} from '../../db/tests/utils'
36import { injectLiveQuery } from '../src/index'
37import { runSuite } from '../../db/tests/conformance/suite'
38import { expectResultSurface } from '../../db/tests/conformance/result-laws'
39import { withScopeSetup } from '../../db/tests/conformance/scope-setup'
40import type {
41 ConformanceResult,
42 ControllableHandle,
43 DeferredSourceHandle,
44 LiveQueryDriver,
45 LiveQueryHandle,
46 QueryBuild,
47 SourceHandle,
48} from '../../db/tests/conformance/contract'
49​
50let sourceSeq = 0
51​
52function writer<T extends { id: string }>(collection: any) {
53 return (type: `insert` | `update` | `delete`, value: T) => {
54 collection.utils.begin()
55 collection.utils.write({ type, value })
56 collection.utils.commit()
57 }
59​
60function makeSource<T extends { id: string }>(
61 initialData: ReadonlyArray<T>,
62): SourceHandle<T> {
63 const collection = createCollection(
64 mockSyncCollectionOptions<T>({
65 id: `conformance-angular-${sourceSeq++}`,
66 getKey: (r) => r.id,
67 initialData: [...initialData],
68 }),
69 )
70 const write = writer<T>(collection)
71 return {
72 collection,
73 insert: (row) => write(`insert`, row),
74 update: (row) => write(`update`, row),
75 remove: (row) => write(`delete`, row),
76 }
78​
79function makeDeferredSource<
80 T extends { id: string },
81>(): DeferredSourceHandle<T> {
82 const collection = createCollection(
83 mockSyncCollectionOptionsNoInitialState<T>({
84 id: `conformance-angular-${sourceSeq++}`,
85 getKey: (r) => r.id,
86 }),
87 )
88 collection.startSyncImmediate()
89 const write = writer<T>(collection)
90 return {
91 collection,
92 insert: (row) => write(`insert`, row),
93 update: (row) => write(`update`, row),
94 remove: (row) => write(`delete`, row),
95 emit: (rows) => {
96 collection.utils.begin()
97 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
98 collection.utils.commit()
99 },
100 markReady: () => collection.utils.markReady(),
101 }
103​
104function makePrecreated(build: QueryBuild, opts?: { startSync?: boolean }) {
105 const collection = createLiveQueryCollection({
106 query: build as any,
107 startSync: opts?.startSync ?? true,
108 })
109 return { collection }
111​
112function makeErrorSource() {
113 const expectedError = new Error(`conformance: sync failure`)
114 let startup: { returned: true } | { returned: false; error: unknown } = {
115 returned: true,
116 }
117 const collection = createCollection<{ id: string }>({
118 id: `conformance-angular-err-${sourceSeq++}`,
119 getKey: (r) => r.id,
120 startSync: false,
121 sync: {
122 sync: () => {
123 throw expectedError
124 },
125 },
126 })
127 try {
128 collection.startSyncImmediate()
129 } catch (error) {
130 startup = { returned: false, error }
131 }
132 return { collection, expectedError, startup }
134​
135async function settle() {
136 await new Promise((resolve) => setTimeout(resolve, 0))
137 await new Promise((resolve) => setTimeout(resolve, 50))
139​
140function makeHandle(result: any, destroy: () => void): LiveQueryHandle {
141 return {
142 current(): ConformanceResult {
143 return expectResultSurface({
144 data: result.data(),
145 state: result.state(),
146 status: result.status(),
147 isReady: result.isReady(),
148 isError: result.isError(),
149 // angular-db exposes no `isEnabled`; derive it from status (status-derived).
150 isEnabled: result.status() !== `disabled`,
151 })
152 },
153 flush: settle,
154 async apply(fn: () => void) {
155 fn()
156 await settle()
157 },
158 unmount() {
159 destroy()
160 },
161 }
163​
164function inCtx(fn: () => any): { result: any; destroy: () => void } {
165 const parent = TestBed.inject(EnvironmentInjector)
166 const injector = createEnvironmentInjector([], parent)
167 let result: any
168 withScopeSetup(
169 () =>
170 runInInjectionContext(injector, () => {
171 result = fn()
172 }),
173 () => injector.destroy(),
174 )
175 return { result, destroy: () => injector.destroy() }
177​
178function mount(build: QueryBuild) {
179 const { result, destroy } = inCtx(() => injectLiveQuery(build as any))
180 return makeHandle(result, destroy)
182​
183function mountCollection(collection: any) {
184 const { result, destroy } = inCtx(() => injectLiveQuery(collection))
185 return makeHandle(result, destroy)
187​
188function mountConfig(build: QueryBuild) {
189 const { result, destroy } = inCtx(() => injectLiveQuery({ query: build }))
190 return makeHandle(result, destroy)
192​
193function mountDisabled() {
194 const { result, destroy } = inCtx(() => injectLiveQuery(() => null))
195 return makeHandle(result, destroy)
197​
198function mountControllable<P>(
199 build: (q: any, param: P) => any,
200 initial: P,
201): ControllableHandle<P> {
202 const param = signal<P>(initial)
203 const { result, destroy } = inCtx(() =>
204 injectLiveQuery({
205 params: () => ({ value: param() }),
206 query: ({ params, q }: any) => build(q, params.value),
207 }),
208 )
209 const handle = makeHandle(result, destroy)
210 return {
211 ...handle,
212 async setParam(next: P) {
213 param.set(next)
214 await settle()
215 },
216 }
218​
219const angularDriver: LiveQueryDriver = {
220 name: `angular`,
221 disabledRepresentation: `empty-reactive`,
222 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
223 makeSource,
224 makeDeferredSource,
225 makePrecreated,
226 makeErrorSource,
227 mount,
228 mountControllable,
229 mountCollection,
230 mountConfig,
231 mountDisabled,
232 knownGaps: [],
233 features: { serverSnapshot: false, suspense: false },
235​
236describe(`owned native scope setup`, () => {
237 it(`keeps a successful scope alive until explicit disposal`, () => {
238 let calls = 0
239 const handle = inCtx(() => {
240 inject(DestroyRef).onDestroy(() => {
241 calls++
242 })
243 return 7
244 })
245 expect(calls).toBe(0)
246 handle.destroy()
247 expect(calls).toBe(1)
248 })
249​
250 it.each([false, true])(
251 `disposes failed setup and retains errors, cleanupFails=%s`,
252 (cleanupFails) => {
253 const primary = new Error(`scope setup failure`)
254 const secondary = new Error(`scope cleanup failure`)
255 let calls = 0
256 let caught: unknown
257 try {
258 inCtx(() => {
259 inject(DestroyRef).onDestroy(() => {
260 calls++
261 if (cleanupFails) throw secondary
262 })
263 throw primary
264 })
265 } catch (error) {
266 caught = error
267 }
268 expect(calls).toBe(1)
269 if (cleanupFails) {
270 expect(caught).toBeInstanceOf(AggregateError)
271 expect((caught as AggregateError).errors).toEqual([primary, secondary])
272 expect((caught as AggregateError).cause).toBe(primary)
273 } else expect(caught).toBe(primary)
274 },
275 )
276})
277​
278runSuite(angularDriver)
279it(`preserves raw result types through the actual driver reader`, () => {
280 const raw: Record<string, unknown> = {
281 data: [{ id: `a`, value: undefined }],
282 state: new Map(),
283 status: `disabled`,
284 isReady: false,
285 isError: false,
286 isEnabled: false,
287 }
288 const result = Object.fromEntries(
289 Object.keys(raw).map((key) => [key, () => raw[key]]),
290 )
291 const handle = makeHandle(result, () => {})
292 try {
293 const healthy = handle.current()
294 expect(healthy.data).toBe(raw.data)
295 expect(healthy.state).toBe(raw.state)
296 expect(healthy.isReady).toBe(false)
297 expect(healthy.isError).toBe(false)
298 expect(healthy.isEnabled).toBe(false)
299 for (const key of [`status`, `isReady`, `isError`]) {
300 const original = raw[key]
301 delete raw[key]
302 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
303 for (const invalid of key === `status`
304 ? [undefined, 0]
305 : [undefined, 0, ``]) {
306 raw[key] = invalid
307 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
308 }
309 raw[key] = original
310 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
311 }
312 } finally {
313 handle.unmount()
314 }
315})