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

conformance.test.ts

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