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

mutations.suite.ts

404 lines13.7 KB

1/**
2 * Backend mutation tests for on-demand collections.
3 * Helpers below own only test rows/queries; expected values stay in each case.
4 */
5import { randomUUID } from 'node:crypto'
6import { describe, expect, it, vi } from 'vitest'
7import { createLiveQueryCollection, eq, gt, isNull } from '@tanstack/db'
8import { waitForQueryData } from '../utils/helpers'
9import type { E2ETestConfig, User } from '../types'
10​
11export async function withQueryCleanup(
12 run: (
13 own: <T extends { cleanup: () => Promise<void> }>(query: T) => T,
14 ) => Promise<void>,
15) {
16 const queries: Array<{ cleanup: () => Promise<void> }> = []
17 const errors: Array<unknown> = []
18 try {
19 await run((query) => {
20 // Register each returned peer before another constructor or await.
21 queries.push(query)
22 return query
23 })
24 } catch (error) {
25 errors.push(error)
26 } finally {
27 // Retain the fixed peer arrays' concurrent cleanup intent. Each async
28 // callback also captures a synchronous cleanup throw before the next peer.
29 const outcomes = await Promise.allSettled(
30 queries.map(async (query) => {
31 await query.cleanup()
32 }),
33 )
34 for (const outcome of outcomes) {
35 if (outcome.status === 'rejected') errors.push(outcome.reason)
36 }
37 }
38 if (errors.length === 1) throw errors[0]
39 if (errors.length > 1)
40 throw new AggregateError(errors, 'Query history and cleanup failed')
42​
43export function userFixture(
44 name: string,
45 age: number,
46 email: string | null = null,
47): User {
48 return {
49 id: randomUUID(),
50 name,
51 email,
52 age,
53 isActive: true,
54 createdAt: new Date(1_710_381_566_535),
55 metadata: null,
56 deletedAt: null,
57 }
59​
60export function captureUserRows(rows: Iterable<User>): Array<User> {
61 return Array.from(rows, (row) =>
62 structuredClone({
63 id: row.id,
64 name: row.name,
65 email: row.email,
66 age: row.age,
67 isActive: row.isActive,
68 createdAt: row.createdAt,
69 metadata: row.metadata,
70 deletedAt: row.deletedAt,
71 }),
72 )
74​
75export function assertUserRows(
76 actual: Array<User>,
77 expected: Array<User>,
78): void {
79 const byId = (a: User, b: User) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
80 expect([...actual].sort(byId)).toStrictEqual([...expected].sort(byId))
82​
83export function waitForUserRows(
84 query: { values: () => Iterable<User> },
85 expected: Array<User>,
86) {
87 return vi.waitFor(
88 () => {
89 const actual = captureUserRows(query.values())
90 assertUserRows(actual, expected)
91 return actual
92 },
93 { timeout: 5000 },
94 )
96​
97export function waitForOwnedUser(config: E2ETestConfig, expected: User) {
98 return vi.waitFor(
99 () => {
100 const row = config.collections.eager.users.get(expected.id)
101 expect(row).toBeDefined()
102 assertUserRows(captureUserRows([row!]), [expected])
103 },
104 { timeout: 5000 },
105 )
107​
108interface OwnedUsers {
109 track: <T extends { cleanup: () => Promise<void> }>(query: T) => T
110 insert: (row: User) => Promise<() => Promise<void>>
112​
113export async function withOwnedUsers(
114 config: E2ETestConfig,
115 run: (owned: OwnedUsers) => Promise<void>,
116) {
117 if (!config.mutations)
118 throw new Error('Mutations not configured - test cannot run')
119 const mutations = config.mutations
120 const cleanups: Array<() => Promise<void>> = []
121 const errors: Array<unknown> = []
122 try {
123 // Eager mode can pause at zero subscribers. Own this observation before
124 // any writes, and release it last so backing-row cleanup stays observed.
125 const backing = createLiveQueryCollection((q) =>
126 q.from({ user: config.collections.eager.users }),
127 )
128 cleanups.push(() => backing.cleanup())
129 await backing.preload()
130 expect(backing.status).toBe('ready')
131 await run({
132 track(query) {
133 cleanups.push(() => query.cleanup())
134 return query
135 },
136 async insert(row) {
137 const id = row.id
138 let needsDeletion = true
139 const remove = async () => {
140 if (!needsDeletion) return
141 await mutations.deleteUser(id)
142 needsDeletion = false
143 await vi.waitFor(
144 () => {
145 expect(config.collections.eager.users.has(id)).toBe(false)
146 },
147 { timeout: 5000 },
148 )
149 }
150 // Register before the provider call, including ambiguous failed inserts.
151 cleanups.push(remove)
152 await mutations.insertUser(structuredClone(row))
153 await waitForOwnedUser(config, row)
154 return remove
155 },
156 })
157 } catch (error) {
158 errors.push(error)
159 } finally {
160 for (const cleanup of cleanups.reverse()) {
161 try {
162 await cleanup()
163 } catch (error) {
164 errors.push(error)
165 }
166 }
167 }
168 if (errors.length === 1) throw errors[0]
169 if (errors.length > 1)
170 throw new AggregateError(errors, 'User history and cleanup failed')
172​
173export function createMutationsTestSuite(
174 getConfig: () => Promise<E2ETestConfig>,
175) {
176 describe('Mutations Suite', () => {
177 describe('Insert Mutations', () => {
178 it('should insert new record via collection', async () => {
179 const config = await getConfig()
180 await withOwnedUsers(config, async (owned) => {
181 const query = owned.track(
182 createLiveQueryCollection((q) =>
183 q.from({ user: config.collections.onDemand.users }),
184 ),
185 )
186 await query.preload()
187 await waitForQueryData(query, { minSize: 1 })
188 const before = captureUserRows(query.values())
189 const initialSize = query.size
190 expect(initialSize).toBeGreaterThan(0)
191 // This helper drives the backend, not an optimistic collection handler.
192 const row = userFixture('Test User', 42, 'test@example.com')
193 const remove = await owned.insert(row)
194 const observed = await waitForUserRows(query, [...before, row])
195 expect(query.size).toBe(initialSize + 1)
196 const corrupted = structuredClone(observed)
197 corrupted[0]!.age += 1
198 expect(() => assertUserRows(corrupted, [...before, row])).toThrow()
199 await remove()
200 await waitForUserRows(query, before)
201 assertUserRows(observed, [...before, row])
202 })
203 })
204​
205 it('should handle insert appearing in matching queries', async () => {
206 const config = await getConfig()
207 await withOwnedUsers(config, async (owned) => {
208 const query = owned.track(
209 createLiveQueryCollection((q) =>
210 q
211 .from({ user: config.collections.onDemand.users })
212 .where(({ user }) => gt(user.age, 30)),
213 ),
214 )
215 await query.preload()
216 await waitForQueryData(query, { minSize: 1 })
217 const before = captureUserRows(query.values())
218 const initialSize = query.size
219 expect(initialSize).toBeGreaterThan(0)
220 const row = userFixture('Test Match User', 50, 'match@example.com')
221 const remove = await owned.insert(row)
222 await waitForUserRows(query, [...before, row])
223 expect(query.size).toBe(initialSize + 1)
224 await remove()
225 await waitForUserRows(query, before)
226 })
227 })
228 })
229​
230 describe('Update Mutations', () => {
231 it('should handle update that makes record match predicate', async () => {
232 const config = await getConfig()
233 await withOwnedUsers(config, async (owned) => {
234 const query = owned.track(
235 createLiveQueryCollection((q) =>
236 q
237 .from({ user: config.collections.onDemand.users })
238 .where(({ user }) => gt(user.age, 30)),
239 ),
240 )
241 await query.preload()
242 await waitForQueryData(query, { minSize: 1 })
243 const before = captureUserRows(query.values())
244 const row = userFixture('Excluded User', 25)
245 await owned.insert(row)
246 await waitForUserRows(query, before)
247 expect(query.has(row.id)).toBe(false)
248 const initialSize = query.size
249 expect(initialSize).toBeGreaterThan(0)
250 // Known backend row, not a search inside the cold filtered source.
251 await config.mutations!.updateUser(row.id, { age: 35 })
252 const updated = { ...row, age: 35 }
253 await waitForOwnedUser(config, updated)
254 await waitForUserRows(query, [...before, updated])
255 expect(query.size).toBe(initialSize + 1)
256 })
257 })
258​
259 it('should handle update that makes record unmatch predicate', async () => {
260 const config = await getConfig()
261 await withOwnedUsers(config, async (owned) => {
262 const query = owned.track(
263 createLiveQueryCollection((q) =>
264 q
265 .from({ user: config.collections.onDemand.users })
266 .where(({ user }) => gt(user.age, 30)),
267 ),
268 )
269 await query.preload()
270 await waitForQueryData(query, { minSize: 1 })
271 const peers = captureUserRows(query.values())
272 const row = userFixture('Matching Before Update', 45)
273 await owned.insert(row)
274 await waitForUserRows(query, [...peers, row])
275 const initialSize = query.size
276 expect(initialSize).toBeGreaterThan(0)
277 await config.mutations!.updateUser(row.id, { age: 25 })
278 await waitForOwnedUser(config, { ...row, age: 25 })
279 await waitForUserRows(query, peers)
280 expect(query.size).toBe(initialSize - 1)
281 expect(query.has(row.id)).toBe(false)
282 })
283 })
284 })
285​
286 describe('Delete Mutations', () => {
287 it('should handle delete removing record from query', async () => {
288 const config = await getConfig()
289 await withOwnedUsers(config, async (owned) => {
290 const query = owned.track(
291 createLiveQueryCollection((q) =>
292 q.from({ user: config.collections.onDemand.users }),
293 ),
294 )
295 await query.preload()
296 await waitForQueryData(query, { minSize: 1 })
297 const peers = captureUserRows(query.values())
298 const row = userFixture('Owned Delete User', 42)
299 const remove = await owned.insert(row)
300 await waitForUserRows(query, [...peers, row])
301 const initialSize = query.size
302 expect(initialSize).toBeGreaterThan(0)
303 await remove()
304 const observed = await waitForUserRows(query, peers)
305 expect(query.size).toBe(initialSize - 1)
306 expect(query.has(row.id)).toBe(false)
307 expect(() => assertUserRows([...observed, row], peers)).toThrow()
308 })
309 })
310 })
311​
312 describe(`Soft Delete Pattern`, () => {
313 it(`should filter out soft-deleted records`, async () => {
314 await withQueryCleanup(async (own) => {
315 const config = await getConfig()
316 const usersCollection = config.collections.onDemand.users
317​
318 const query = own(
319 createLiveQueryCollection((q) =>
320 q
321 .from({ user: usersCollection })
322 .where(({ user }) => isNull(user.deletedAt)),
323 ),
324 )
325​
326 await query.preload()
327 await waitForQueryData(query, { minSize: 1 })
328​
329 // All results should not be soft-deleted
330 const results = Array.from(query.state.values())
331 expect(results.length).toBeGreaterThan(0)
332 results.forEach((u) => {
333 expect(u.deletedAt).toBeNull()
334 })
335 })
336 })
337​
338 it(`should include soft-deleted records when not filtered`, async () => {
339 await withQueryCleanup(async (own) => {
340 const config = await getConfig()
341 const usersCollection = config.collections.onDemand.users
342​
343 const query = own(
344 createLiveQueryCollection((q) => q.from({ user: usersCollection })),
345 )
346​
347 await query.preload()
348 await waitForQueryData(query, { minSize: 1 })
349​
350 // Should include both deleted and non-deleted
351 const results = Array.from(query.state.values())
352 const hasNotDeleted = results.some((u) => u.deletedAt === null)
353​
354 expect(hasNotDeleted).toBe(true)
355 })
356 })
357 })
358​
359 describe('Mutation with Queries', () => {
360 it('should maintain query state during data changes', async () => {
361 const config = await getConfig()
362 await withOwnedUsers(config, async (owned) => {
363 const query = owned.track(
364 createLiveQueryCollection((q) =>
365 q
366 .from({ user: config.collections.onDemand.users })
367 .where(({ user }) => eq(user.isActive, true))
368 .orderBy(({ user }) => user.age, 'asc')
369 .limit(10),
370 ),
371 )
372 await query.preload()
373 expect(query.size).toBeLessThanOrEqual(10)
374 // All eleven unique ages are below the seeded minimum (-5).
375 // They remove any dependence on the seed's tied boundary identities.
376 const rows = Array.from({ length: 11 }, (_, index) =>
377 userFixture('Owned page ' + index, -1010 + index),
378 )
379 for (const row of rows) await owned.insert(row)
380 await vi.waitFor(
381 () => {
382 expect(captureUserRows(query.values())).toStrictEqual(
383 rows.slice(0, 10),
384 )
385 },
386 { timeout: 5000 },
387 )
388 expect(query.size).toBeLessThanOrEqual(10)
389 await config.mutations!.updateUser(rows[0]!.id, { age: -999 })
390 await waitForOwnedUser(config, { ...rows[0]!, age: -999 })
391 await vi.waitFor(
392 () => {
393 expect(captureUserRows(query.values())).toStrictEqual(
394 rows.slice(1),
395 )
396 },
397 { timeout: 5000 },
398 )
399 expect(query.size).toBeLessThanOrEqual(10)
400 })
401 })
402 })
403 })