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