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

conformance.test.ts

222 lines5.7 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 * `knownGaps` is populated empirically from the run below.
11 */
12import {
13 EnvironmentInjector,
14 createEnvironmentInjector,
15 runInInjectionContext,
16 signal,
17} from '@angular/core'
18import { TestBed } from '@angular/core/testing'
19import {
20 coalesce,
21 count,
22 createCollection,
23 createLiveQueryCollection,
24 createOptimisticAction,
25 eq,
26 gt,
27 sum,
28} from '@tanstack/db'
29import {
30 mockSyncCollectionOptions,
31 mockSyncCollectionOptionsNoInitialState,
32} from '../../db/tests/utils'
33import { injectLiveQuery } from '../src/index'
34import { runSuite } from '../../db/tests/conformance/suite'
35import type {
36 ConformanceResult,
37 ControllableHandle,
38 DeferredSourceHandle,
39 LiveQueryDriver,
40 LiveQueryHandle,
41 QueryBuild,
42 SourceHandle,
43} from '../../db/tests/conformance/contract'
44​
45let sourceSeq = 0
46​
47function writer<T extends { id: string }>(collection: any) {
48 return (type: `insert` | `update` | `delete`, value: T) => {
49 collection.utils.begin()
50 collection.utils.write({ type, value })
51 collection.utils.commit()
52 }
54​
55function makeSource<T extends { id: string }>(
56 initialData: ReadonlyArray<T>,
57): SourceHandle<T> {
58 const collection = createCollection(
59 mockSyncCollectionOptions<T>({
60 id: `conformance-angular-${sourceSeq++}`,
61 getKey: (r) => r.id,
62 initialData: [...initialData],
63 }),
64 )
65 const write = writer<T>(collection)
66 return {
67 collection,
68 insert: (row) => write(`insert`, row),
69 update: (row) => write(`update`, row),
70 remove: (row) => write(`delete`, row),
71 }
73​
74function makeDeferredSource<
75 T extends { id: string },
76>(): DeferredSourceHandle<T> {
77 const collection = createCollection(
78 mockSyncCollectionOptionsNoInitialState<T>({
79 id: `conformance-angular-${sourceSeq++}`,
80 getKey: (r) => r.id,
81 }),
82 )
83 collection.startSyncImmediate()
84 const write = writer<T>(collection)
85 return {
86 collection,
87 insert: (row) => write(`insert`, row),
88 update: (row) => write(`update`, row),
89 remove: (row) => write(`delete`, row),
90 emit: (rows) => {
91 collection.utils.begin()
92 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
93 collection.utils.commit()
94 },
95 markReady: () => collection.utils.markReady(),
96 }
98​
99function makePrecreated(build: QueryBuild, opts?: { startSync?: boolean }) {
100 const collection = createLiveQueryCollection({
101 query: build as any,
102 startSync: opts?.startSync ?? true,
103 })
104 return { collection }
106​
107function makeErrorSource() {
108 const collection = createCollection<{ id: string }>({
109 id: `conformance-angular-err-${sourceSeq++}`,
110 getKey: (r) => r.id,
111 startSync: false,
112 sync: {
113 sync: () => {
114 throw new Error(`conformance: sync failure`)
115 },
116 },
117 })
118 try {
119 collection.startSyncImmediate()
120 } catch {
121 // expected: engine catches the sync error and sets status to `error`
122 }
123 return { collection }
125​
126async function settle() {
127 await new Promise((resolve) => setTimeout(resolve, 0))
128 await new Promise((resolve) => setTimeout(resolve, 50))
130​
131function makeHandle(result: any, destroy: () => void): LiveQueryHandle {
132 return {
133 current(): ConformanceResult {
134 return {
135 data: result.data(),
136 state: result.state(),
137 status: result.status(),
138 isReady: Boolean(result.isReady()),
139 isError: Boolean(result.isError()),
140 // angular-db exposes no `isEnabled`; derive it from status (status-derived).
141 isEnabled: result.status() !== `disabled`,
142 }
143 },
144 flush: settle,
145 async apply(fn: () => void) {
146 fn()
147 await settle()
148 },
149 unmount() {
150 destroy()
151 },
152 }
154​
155function inCtx(fn: () => any): { result: any; destroy: () => void } {
156 const parent = TestBed.inject(EnvironmentInjector)
157 const injector = createEnvironmentInjector([], parent)
158 let result: any
159 runInInjectionContext(injector, () => {
160 result = fn()
161 })
162 return { result, destroy: () => injector.destroy() }
164​
165function mount(build: QueryBuild) {
166 const { result, destroy } = inCtx(() => injectLiveQuery(build as any))
167 return makeHandle(result, destroy)
169​
170function mountCollection(collection: any) {
171 const { result, destroy } = inCtx(() => injectLiveQuery(collection))
172 return makeHandle(result, destroy)
174​
175function mountConfig(build: QueryBuild) {
176 const { result, destroy } = inCtx(() => injectLiveQuery({ query: build }))
177 return makeHandle(result, destroy)
179​
180function mountDisabled() {
181 const { result, destroy } = inCtx(() => injectLiveQuery(() => null))
182 return makeHandle(result, destroy)
184​
185function mountControllable<P>(
186 build: (q: any, param: P) => any,
187 initial: P,
188): ControllableHandle<P> {
189 const param = signal<P>(initial)
190 const { result, destroy } = inCtx(() =>
191 injectLiveQuery({
192 params: () => ({ value: param() }),
193 query: ({ params, q }: any) => build(q, params.value),
194 }),
195 )
196 const handle = makeHandle(result, destroy)
197 return {
198 ...handle,
199 async setParam(next: P) {
200 param.set(next)
201 await settle()
202 },
203 }
205​
206const angularDriver: LiveQueryDriver = {
207 name: `angular`,
208 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
209 makeSource,
210 makeDeferredSource,
211 makePrecreated,
212 makeErrorSource,
213 mount,
214 mountControllable,
215 mountCollection,
216 mountConfig,
217 mountDisabled,
218 knownGaps: [],
219 features: { serverSnapshot: false, suspense: false },
221​
222runSuite(angularDriver)