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

mutations.suite.ts

318 lines9.8 KB

1/**
2 * Mutations Test Suite
3 *
4 * Tests data mutations with on-demand syncMode
5 */
6​
7import { randomUUID } from 'node:crypto'
8import { describe, expect, it } from 'vitest'
9import { createLiveQueryCollection, eq, gt, isNull } from '@tanstack/db'
10import { waitFor, waitForQueryData } from '../utils/helpers'
11import type { E2ETestConfig } from '../types'
12​
13export function createMutationsTestSuite(
14 getConfig: () => Promise<E2ETestConfig>,
15) {
16 describe(`Mutations Suite`, () => {
17 describe(`Insert Mutations`, () => {
18 it(`should insert new record via collection`, async () => {
19 const config = await getConfig()
20​
21 if (!config.mutations) {
22 throw new Error(`Mutations not configured - test cannot run`)
23 }
24​
25 const usersCollection = config.collections.onDemand.users
26​
27 // Load initial data
28 const query = createLiveQueryCollection((q) =>
29 q.from({ user: usersCollection }),
30 )
31​
32 await query.preload()
33 await waitForQueryData(query, { minSize: 1 })
34 const initialSize = query.size
35 expect(initialSize).toBeGreaterThan(0)
36​
37 // Perform actual INSERT via backend
38 const newUserId = randomUUID()
39 await config.mutations.insertUser({
40 id: newUserId,
41 name: `Test User`,
42 email: `test@example.com`,
43 age: 42,
44 isActive: true,
45 createdAt: new Date(),
46 metadata: null,
47 deletedAt: null,
48 })
49​
50 // Wait for sync to propagate the new record (Electric only)
51 await waitFor(() => query.size > initialSize, {
52 timeout: 5000,
53 message: `New record did not appear in query`,
54 })
55​
56 expect(query.size).toBe(initialSize + 1)
57​
58 // Clean up the inserted row
59 await config.mutations.deleteUser(newUserId)
60​
61 // Wait for deletion to propagate if using async replication (e.g., Electric)
62 // Check the eager collection since it continuously syncs all data
63 if (config.hasReplicationLag) {
64 await waitFor(() => !config.collections.eager.users.has(newUserId), {
65 timeout: 5000,
66 message: `Deletion of user ${newUserId} did not propagate`,
67 })
68 }
69​
70 await query.cleanup()
71 })
72​
73 it(`should handle insert appearing in matching queries`, async () => {
74 const config = await getConfig()
75​
76 if (!config.mutations) {
77 throw new Error(`Mutations not configured - test cannot run`)
78 }
79​
80 const usersCollection = config.collections.onDemand.users
81​
82 const query = createLiveQueryCollection((q) =>
83 q
84 .from({ user: usersCollection })
85 .where(({ user }) => gt(user.age, 30)),
86 )
87​
88 await query.preload()
89 await waitForQueryData(query, { minSize: 1 })
90 const initialSize = query.size
91 expect(initialSize).toBeGreaterThan(0)
92​
93 // Insert record that MATCHES predicate (age > 30)
94 const newUserId = randomUUID()
95 await config.mutations.insertUser({
96 id: newUserId,
97 name: `Test Match User`,
98 email: `match@example.com`,
99 age: 50,
100 isActive: true,
101 createdAt: new Date(),
102 metadata: null,
103 deletedAt: null,
104 })
105​
106 // Wait for sync to propagate (Electric only)
107 await waitFor(() => query.size > initialSize, {
108 timeout: 5000,
109 message: `Matching insert did not appear in query`,
110 })
111​
112 expect(query.size).toBe(initialSize + 1)
113​
114 // Clean up the inserted row
115 await config.mutations.deleteUser(newUserId)
116​
117 // Wait for deletion to propagate if using async replication (e.g., Electric)
118 // Check the eager collection since it continuously syncs all data
119 if (config.hasReplicationLag) {
120 await waitFor(() => !config.collections.eager.users.has(newUserId), {
121 timeout: 5000,
122 message: `Deletion of user ${newUserId} did not propagate`,
123 })
124 }
125​
126 await query.cleanup()
127 })
128 })
129​
130 describe(`Update Mutations`, () => {
131 it(`should handle update that makes record match predicate`, async () => {
132 const config = await getConfig()
133​
134 if (!config.mutations) {
135 throw new Error(`Mutations not configured - test cannot run`)
136 }
137​
138 const usersCollection = config.collections.onDemand.users
139​
140 const query = createLiveQueryCollection((q) =>
141 q
142 .from({ user: usersCollection })
143 .where(({ user }) => gt(user.age, 30)),
144 )
145​
146 await query.preload()
147 await waitForQueryData(query, { minSize: 1 })
148 const initialSize = query.size
149 expect(initialSize).toBeGreaterThan(0)
150​
151 // Find a user with age <= 30 in the full collection
152 const allUsers = Array.from(usersCollection.state.values())
153 const userToUpdate = allUsers.find((u) => u.age <= 30)
154​
155 if (userToUpdate) {
156 // Update age to 35 (matches predicate)
157 await config.mutations.updateUser(userToUpdate.id, { age: 35 })
158​
159 // Wait for Electric to sync and query to show updated record
160 await waitFor(() => query.size > initialSize, {
161 timeout: 5000,
162 message: `Updated record did not appear in query`,
163 })
164​
165 expect(query.size).toBe(initialSize + 1)
166 }
167​
168 await query.cleanup()
169 })
170​
171 it(`should handle update that makes record unmatch predicate`, async () => {
172 const config = await getConfig()
173​
174 if (!config.mutations) {
175 throw new Error(`Mutations not configured - test cannot run`)
176 }
177​
178 const usersCollection = config.collections.onDemand.users
179​
180 const query = createLiveQueryCollection((q) =>
181 q
182 .from({ user: usersCollection })
183 .where(({ user }) => gt(user.age, 30)),
184 )
185​
186 await query.preload()
187 await waitForQueryData(query, { minSize: 1 })
188 const initialSize = query.size
189 expect(initialSize).toBeGreaterThan(0)
190​
191 // Get a user currently in the query (age > 30)
192 const queryUsers = Array.from(query.state.values())
193 const userToUpdate = queryUsers[0]
194​
195 if (userToUpdate) {
196 // Update age to 25 (no longer matches predicate)
197 await config.mutations.updateUser(userToUpdate.id, { age: 25 })
198​
199 // Wait for Electric to sync and query to remove record
200 await waitFor(() => query.size < initialSize, {
201 timeout: 5000,
202 message: `Updated record was not removed from query`,
203 })
204​
205 expect(query.size).toBe(initialSize - 1)
206 }
207​
208 await query.cleanup()
209 })
210 })
211​
212 describe(`Delete Mutations`, () => {
213 it(`should handle delete removing record from query`, async () => {
214 const config = await getConfig()
215​
216 if (!config.mutations) {
217 throw new Error(`Mutations not configured - test cannot run`)
218 }
219​
220 const usersCollection = config.collections.onDemand.users
221​
222 const query = createLiveQueryCollection((q) =>
223 q.from({ user: usersCollection }),
224 )
225​
226 await query.preload()
227 await waitForQueryData(query, { minSize: 1 })
228 const initialSize = query.size
229 expect(initialSize).toBeGreaterThan(0)
230​
231 // Get a user and delete it
232 const users = Array.from(query.state.values())
233 const userToDelete = users[0]
234​
235 if (userToDelete) {
236 await config.mutations.deleteUser(userToDelete.id)
237​
238 // Wait for delete to sync
239 await waitFor(() => query.size < initialSize, {
240 timeout: 5000,
241 message: `Delete did not sync to query`,
242 })
243​
244 expect(query.size).toBe(initialSize - 1)
245 }
246​
247 await query.cleanup()
248 })
249 })
250​
251 describe(`Soft Delete Pattern`, () => {
252 it(`should filter out soft-deleted records`, async () => {
253 const config = await getConfig()
254 const usersCollection = config.collections.onDemand.users
255​
256 const query = createLiveQueryCollection((q) =>
257 q
258 .from({ user: usersCollection })
259 .where(({ user }) => isNull(user.deletedAt)),
260 )
261​
262 await query.preload()
263 await waitForQueryData(query, { minSize: 1 })
264​
265 // All results should not be soft-deleted
266 const results = Array.from(query.state.values())
267 expect(results.length).toBeGreaterThan(0)
268 results.forEach((u) => {
269 expect(u.deletedAt).toBeNull()
270 })
271​
272 await query.cleanup()
273 })
274​
275 it(`should include soft-deleted records when not filtered`, async () => {
276 const config = await getConfig()
277 const usersCollection = config.collections.onDemand.users
278​
279 const query = createLiveQueryCollection((q) =>
280 q.from({ user: usersCollection }),
281 )
282​
283 await query.preload()
284 await waitForQueryData(query, { minSize: 1 })
285​
286 // Should include both deleted and non-deleted
287 const results = Array.from(query.state.values())
288 const hasNotDeleted = results.some((u) => u.deletedAt === null)
289​
290 expect(hasNotDeleted).toBe(true)
291​
292 await query.cleanup()
293 })
294 })
295​
296 describe(`Mutation with Queries`, () => {
297 it(`should maintain query state during data changes`, async () => {
298 const config = await getConfig()
299 const usersCollection = config.collections.onDemand.users
300​
301 const query = createLiveQueryCollection((q) =>
302 q
303 .from({ user: usersCollection })
304 .where(({ user }) => eq(user.isActive, true))
305 .orderBy(({ user }) => user.age, `asc`)
306 .limit(10),
307 )
308​
309 await query.preload()
310​
311 // Test structure: Mutations should maintain pagination state
312 expect(query.size).toBeLessThanOrEqual(10)
313​
314 await query.cleanup()
315 })
316 })
317 })