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

conformance.test.ts

486 lines14.3 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 { afterEach, beforeEach, describe, expect, it } from 'vitest'
13import {
14 Component,
15 DestroyRef,
16 EnvironmentInjector,
17 ErrorHandler,
18 createEnvironmentInjector,
19 effect,
20 inject,
21 input,
22 runInInjectionContext,
23 signal,
24} from '@angular/core'
25import { TestBed } from '@angular/core/testing'
26import {
27 coalesce,
28 count,
29 createCollection,
30 createLiveQueryCollection,
31 createOptimisticAction,
32 eq,
33 groupKeys,
34 gt,
35 sum,
36} from '@tanstack/db'
37import {
38 mockSyncCollectionOptions,
39 mockSyncCollectionOptionsNoInitialState,
40} from '../../db/tests/utils'
41import { injectLiveQuery } from '../src/index'
42import { runSuite } from '../../db/tests/conformance/suite'
43import { createPublicationLog } from '../../db/tests/conformance/publication-log'
44import { makeLaggingSource } from '../../db/tests/conformance/lagging-source'
45import { makeSyncSource } from '../../db/tests/conformance/sync-source'
46import { makeErrorSource as makeSharedErrorSource } from '../../db/tests/conformance/error-source'
47import { expectResultSurface } from '../../db/tests/conformance/result-laws'
48import { withScopeSetup } from '../../db/tests/conformance/scope-setup'
49import type { PooledLiveQueries } from '@tanstack/db'
50import type {
51 ConformanceResult,
52 ControllableHandle,
53 DeferredSourceHandle,
54 LiveQueryDriver,
55 LiveQueryHandle,
56 QueryBuild,
57 SourceHandle,
58} from '../../db/tests/conformance/contract'
59​
60let sourceSeq = 0
61​
62function writer<T extends { id: string }>(collection: any) {
63 return (type: `insert` | `update` | `delete`, value: T) => {
64 collection.utils.begin()
65 collection.utils.write({ type, value })
66 collection.utils.commit()
67 }
69​
70function makeSource<T extends { id: string }>(
71 initialData: ReadonlyArray<T>,
72 collectionId?: string,
73): SourceHandle<T> {
74 const collection = createCollection(
75 mockSyncCollectionOptions<T>({
76 id: collectionId ?? `conformance-angular-${sourceSeq++}`,
77 getKey: (r) => r.id,
78 initialData: [...initialData],
79 }),
80 )
81 const write = writer<T>(collection)
82 return {
83 collection,
84 insert: (row) => write(`insert`, row),
85 update: (row) => write(`update`, row),
86 remove: (row) => write(`delete`, row),
87 }
89​
90function makeDeferredSource<
91 T extends { id: string },
92>(): DeferredSourceHandle<T> {
93 const collection = createCollection(
94 mockSyncCollectionOptionsNoInitialState<T>({
95 id: `conformance-angular-${sourceSeq++}`,
96 getKey: (r) => r.id,
97 }),
98 )
99 collection.startSyncImmediate()
100 const write = writer<T>(collection)
101 return {
102 collection,
103 insert: (row) => write(`insert`, row),
104 update: (row) => write(`update`, row),
105 remove: (row) => write(`delete`, row),
106 emit: (rows) => {
107 collection.utils.begin()
108 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
109 collection.utils.commit()
110 },
111 markReady: () => collection.utils.markReady(),
112 }
114​
115function makePrecreated(
116 build: QueryBuild,
117 opts?: { startSync?: boolean; gcTime?: number },
118) {
119 const collection = createLiveQueryCollection({
120 query: build as any,
121 startSync: opts?.startSync ?? true,
122 gcTime: opts?.gcTime,
123 })
124 return { collection }
126​
127function makeErrorSource(kind: `fail` | `crash`) {
128 return makeSharedErrorSource(
129 createCollection,
130 `conformance-angular-err-${sourceSeq++}`,
131 kind,
132 )
134​
135async function settle() {
136 await new Promise((resolve) => setTimeout(resolve, 0))
137 await new Promise((resolve) => setTimeout(resolve, 50))
139​
140// Angular reports an error that a binding's root effect throws, such as a
141// rejected query input, to the application ErrorHandler. The driver records
142// them, and a handle rethrows the first one reported since it mounted on its
143// next read or flush: that is the rejection the contract observes. Mounts that
144// fail run one at a time, so this attributes each error to its mount. Every
145// recorded error must be claimed by a read before its test ends, so an error
146// that no scenario expects still fails its test.
147const reported: Array<{ error: unknown; claimed: boolean }> = []
148const reportedSince = new WeakMap<object, number>()
149​
150beforeEach(() => {
151 reported.length = 0
152 TestBed.resetTestingModule()
153 TestBed.configureTestingModule({
154 rethrowApplicationErrors: false,
155 providers: [
156 {
157 provide: ErrorHandler,
158 useValue: {
159 handleError: (error: unknown) =>
160 reported.push({ error, claimed: false }),
161 },
162 },
163 ],
164 })
165})
166​
167afterEach(() => {
168 expect(
169 reported.filter(({ claimed }) => !claimed).map(({ error }) => error),
170 `errors reported to ErrorHandler that no read observed`,
171 ).toEqual([])
172})
173​
174function rethrowReported(result: any): void {
175 const entry = reported.slice(reportedSince.get(result) ?? 0)[0]
176 if (entry) {
177 entry.claimed = true
178 throw entry.error
179 }
181​
182function makeHandle(result: any, destroy: () => void): LiveQueryHandle {
183 return {
184 collection: () => result.collection(),
185 current(): ConformanceResult {
186 rethrowReported(result)
187 return expectResultSurface({
188 data: result.data(),
189 state: result.state(),
190 status: result.status(),
191 isReady: result.isReady(),
192 isLoadingError: result.isLoadingError(),
193 isCrashed: result.isCrashed(),
194 isSyncError: result.isSyncError(),
195 // angular-db exposes no `isEnabled`; derive it from status (status-derived).
196 isEnabled: result.status() !== `disabled`,
197 health: result.health(),
198 })
199 },
200 async flush() {
201 await settle()
202 rethrowReported(result)
203 },
204 async apply(fn: () => void) {
205 fn()
206 await settle()
207 rethrowReported(result)
208 },
209 unmount() {
210 destroy()
211 },
212 }
214​
215function inCtx(fn: () => any): { result: any; destroy: () => void } {
216 const parent = TestBed.inject(EnvironmentInjector)
217 const since = reported.length
218 const injector = createEnvironmentInjector([], parent)
219 let result: any
220 withScopeSetup(
221 () =>
222 runInInjectionContext(injector, () => {
223 result = fn()
224 }),
225 () => injector.destroy(),
226 )
227 if (result && typeof result === `object`) reportedSince.set(result, since)
228 return { result, destroy: () => injector.destroy() }
230​
231function mount(build: QueryBuild) {
232 const { result, destroy } = inCtx(() => injectLiveQuery(build as any))
233 return makeHandle(result, destroy)
235​
236function mountCollection(collection: any) {
237 const { result, destroy } = inCtx(() => injectLiveQuery(collection))
238 return makeHandle(result, destroy)
240​
241function mountConfig(
242 build: QueryBuild,
243 opts?: { gcTime?: number; pool?: PooledLiveQueries },
244) {
245 const { result, destroy } = inCtx(() =>
246 injectLiveQuery({ query: build, ...opts }),
247 )
248 return makeHandle(result, destroy)
250​
251function mountDisabled() {
252 const { result, destroy } = inCtx(() => injectLiveQuery(() => null))
253 return makeHandle(result, destroy)
255​
256function mountControllable<P>(
257 build: (q: any, param: P) => any,
258 initial: P,
259 opts?: { pool?: PooledLiveQueries },
260): ControllableHandle<P> {
261 const param = signal<P>(initial)
262 const published = createPublicationLog()
263 const { result, destroy } = inCtx(() => {
264 const query = injectLiveQuery({
265 params: () => ({ value: param() }),
266 query: ({ params, q }: any) => build(q, params.value),
267 pool: opts?.pool,
268 })
269 // Angular renders the value each effect run reads.
270 effect(() => {
271 published.record(query.data(), query.state())
272 })
273 return query
274 })
275 const handle = makeHandle(result, destroy)
276 return {
277 ...handle,
278 publications: published.values,
279 statePublications: published.stateValues,
280 async setParam(next: P) {
281 param.set(next)
282 // The first paint after the change: the framework has flushed its
283 // reactive work, but no later task has run.
284 TestBed.tick()
285 published.record(result.data(), result.state())
286 await settle()
287 },
288 }
290​
291const angularDriver: LiveQueryDriver = {
292 name: `angular`,
293 // Reactive reads decide when the query compiles again.
294 comparesQueryIdentity: false,
295 disabledRepresentation: `empty-reactive`,
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-angular-lagging-${sourceSeq++}`,
303 ),
304 makeSyncSource: <T extends { id: string }>(data: ReadonlyArray<T>) =>
305 makeSyncSource<T>(
306 createCollection,
307 `conformance-angular-health-${sourceSeq++}`,
308 data,
309 ),
310 makePrecreated,
311 makeErrorSource,
312 mount,
313 mountControllable,
314 mountCollection,
315 mountConfig,
316 mountDisabled,
317 knownGaps: [],
318 features: { serverSnapshot: false, suspense: false, pooledEqFilters: true },
320​
321describe(`owned native scope setup`, () => {
322 it(`keeps a successful scope alive until explicit disposal`, () => {
323 let calls = 0
324 const handle = inCtx(() => {
325 inject(DestroyRef).onDestroy(() => {
326 calls++
327 })
328 return 7
329 })
330 expect(calls).toBe(0)
331 handle.destroy()
332 expect(calls).toBe(1)
333 })
334​
335 it.each([false, true])(
336 `disposes failed setup and retains errors, cleanupFails=%s`,
337 (cleanupFails) => {
338 const primary = new Error(`scope setup failure`)
339 const secondary = new Error(`scope cleanup failure`)
340 let calls = 0
341 let caught: unknown
342 try {
343 inCtx(() => {
344 inject(DestroyRef).onDestroy(() => {
345 calls++
346 if (cleanupFails) throw secondary
347 })
348 throw primary
349 })
350 } catch (error) {
351 caught = error
352 }
353 expect(calls).toBe(1)
354 if (cleanupFails) {
355 expect(caught).toBeInstanceOf(AggregateError)
356 expect((caught as AggregateError).errors).toEqual([primary, secondary])
357 expect((caught as AggregateError).cause).toBe(primary)
358 } else expect(caught).toBe(primary)
359 },
360 )
361})
362​
363runSuite(angularDriver)
364​
365it(`reports a disabled query as ready before effects run`, () => {
366 const mounted = inCtx(() => injectLiveQuery(() => null))
367 try {
368 expect(mounted.result.status()).toBe(`disabled`)
369 expect(mounted.result.isReady()).toBe(true)
370 } finally {
371 mounted.destroy()
372 }
373})
374​
375/**
376 * Angular component boundary: required inputs are assigned after field
377 * initialization. A reactive live-query option may read an input when Angular
378 * first runs effects, but construction must not read it before `setInput`.
379 * The model is a full filter of two fixed source rows at each input value.
380 * This checks rendered public data after change detection, not every possible
381 * framework scheduling cut or the shared query model's other laws.
382 */
383it(`waits for required inputs before evaluating a reactive live query`, async () => {
384 const source = createCollection(
385 mockSyncCollectionOptions<{ id: string; age: number }>({
386 id: `angular-required-input-query`,
387 getKey: (row) => row.id,
388 initialData: [
389 { id: `a`, age: 20 },
390 { id: `b`, age: 40 },
391 ],
392 }),
393 )
394​
395 @Component({
396 inputs: [{ name: `minAge`, required: true }],
397 template: `{{ live.data().length }}`,
398 })
399 class RequiredInputQuery {
400 minAge = input.required<number>()
401 live = injectLiveQuery({
402 params: () => ({ minAge: this.minAge() }),
403 query: ({ params, q }) =>
404 q
405 .from({ person: source })
406 .where(({ person }) => gt(person.age, params.minAge))
407 .select(({ person }) => ({ id: person.id, age: person.age })),
408 })
409 }
410​
411 // This suite uses Angular's JIT test environment, which does not infer the
412 // signal-input flag from `input.required()`. Supply the same input metadata
413 // that Angular's AOT compiler emits; TestBed still constructs the component,
414 // assigns the input, runs its effects, and renders the public result.
415 const definition = (
416 RequiredInputQuery as unknown as {
417 ɵcmp: { inputs: { minAge: [string, number, null] } }
418 }
419 ).ɵcmp
420 definition.inputs.minAge = [`minAge`, 1, null]
421​
422 const fixture = TestBed.createComponent(RequiredInputQuery)
423 try {
424 fixture.componentRef.setInput(`minAge`, 30)
425 fixture.detectChanges()
426 await settle()
427 fixture.detectChanges()
428 expect(fixture.nativeElement.textContent.trim()).toBe(`1`)
429 expect(fixture.componentInstance.live.data().map((row) => row.id)).toEqual([
430 `b`,
431 ])
432​
433 fixture.componentRef.setInput(`minAge`, 10)
434 fixture.detectChanges()
435 await settle()
436 fixture.detectChanges()
437 expect(fixture.nativeElement.textContent.trim()).toBe(`2`)
438 expect(fixture.componentInstance.live.data().map((row) => row.id)).toEqual([
439 `a`,
440 `b`,
441 ])
442 } finally {
443 fixture.destroy()
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 health: undefined,
458 }
459 const result = Object.fromEntries(
460 Object.keys(raw).map((key) => [key, () => raw[key]]),
461 )
462 const handle = makeHandle(result, () => {})
463 try {
464 const healthy = handle.current()
465 expect(healthy.data).toBe(raw.data)
466 expect(healthy.state).toBe(raw.state)
467 expect(healthy.isReady).toBe(false)
468 expect(healthy.isLoadingError).toBe(false)
469 expect(healthy.isEnabled).toBe(false)
470 for (const key of [`status`, `isReady`, `isLoadingError`]) {
471 const original = raw[key]
472 delete raw[key]
473 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
474 for (const invalid of key === `status`
475 ? [undefined, 0]
476 : [undefined, 0, ``]) {
477 raw[key] = invalid
478 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
479 }
480 raw[key] = original
481 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
482 }
483 } finally {
484 handle.unmount()
485 }
486})