-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathelectric-live-query.test.ts
More file actions
339 lines (299 loc) · 8.33 KB
/
electric-live-query.test.ts
File metadata and controls
339 lines (299 loc) · 8.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import { beforeEach, describe, expect, it, vi } from "vitest"
import {
createCollection,
createLiveQueryCollection,
eq,
gt,
} from "@tanstack/db"
import { electricCollectionOptions } from "../src/electric"
import type { ElectricCollectionUtils } from "../src/electric"
import type { Collection } from "@tanstack/db"
import type { Message } from "@electric-sql/client"
import type { StandardSchemaV1 } from "@standard-schema/spec"
// Sample user type for tests
type User = {
id: number
name: string
age: number
email: string
active: boolean
}
// Sample data for tests
const sampleUsers: Array<User> = [
{
id: 1,
name: `Alice`,
age: 25,
email: `alice@example.com`,
active: true,
},
{
id: 2,
name: `Bob`,
age: 19,
email: `bob@example.com`,
active: true,
},
{
id: 3,
name: `Charlie`,
age: 30,
email: `charlie@example.com`,
active: false,
},
{
id: 4,
name: `Dave`,
age: 22,
email: `dave@example.com`,
active: true,
},
]
// Mock the ShapeStream module
const mockSubscribe = vi.fn()
const mockStream = {
subscribe: mockSubscribe,
}
vi.mock(`@electric-sql/client`, async () => {
const actual = await vi.importActual(`@electric-sql/client`)
return {
...actual,
ShapeStream: vi.fn(() => mockStream),
}
})
describe.each([
[`autoIndex enabled (default)`, `eager` as const],
[`autoIndex disabled`, `off` as const],
])(`Electric Collection with Live Query - %s`, (description, autoIndex) => {
let electricCollection: Collection<
User,
number,
ElectricCollectionUtils,
StandardSchemaV1<unknown, unknown>,
User
>
let subscriber: (messages: Array<Message<User>>) => void
function createElectricUsersCollection() {
vi.clearAllMocks()
// Reset mock subscriber
mockSubscribe.mockImplementation((callback) => {
subscriber = callback
return () => {}
})
// Create Electric collection with specified autoIndex
const config = {
id: `electric-users`,
shapeOptions: {
url: `http://test-url`,
params: {
table: `users`,
},
},
startSync: true,
getKey: (user: User) => user.id,
autoIndex,
}
const options = electricCollectionOptions(config)
return createCollection(options)
}
function simulateInitialSync(users: Array<User> = sampleUsers) {
const messages: Array<Message<User>> = users.map((user) => ({
key: user.id.toString(),
value: user,
headers: { operation: `insert` },
}))
messages.push({
headers: { control: `up-to-date` },
})
subscriber(messages)
}
function simulateMustRefetch() {
subscriber([
{
headers: { control: `must-refetch` },
},
])
}
function simulateResync(users: Array<User>) {
const messages: Array<Message<User>> = users.map((user) => ({
key: user.id.toString(),
value: user,
headers: { operation: `insert` },
}))
messages.push({
headers: { control: `up-to-date` },
})
subscriber(messages)
}
beforeEach(() => {
electricCollection = createElectricUsersCollection()
})
it(`should handle basic must-refetch with filtered live query`, () => {
// Create a live query with WHERE clause
const activeLiveQuery = createLiveQueryCollection({
id: `active-users-live-query`,
startSync: true,
query: (q) =>
q
.from({ user: electricCollection })
.where(({ user }) => eq(user.active, true))
.select(({ user }) => ({
id: user.id,
name: user.name,
active: user.active,
})),
})
// Initial sync
simulateInitialSync()
expect(electricCollection.status).toBe(`ready`)
expect(electricCollection.size).toBe(4)
expect(activeLiveQuery.status).toBe(`ready`)
expect(activeLiveQuery.size).toBe(3) // Only active users
// Must-refetch and resync with updated data
simulateMustRefetch()
const updatedUsers = [
{
id: 1,
name: `Alice Updated`,
age: 26,
email: `alice@example.com`,
active: true,
},
{ id: 5, name: `Eve`, age: 24, email: `eve@example.com`, active: true },
{
id: 6,
name: `Frank`,
age: 35,
email: `frank@example.com`,
active: false,
},
]
simulateResync(updatedUsers)
// BUG: Live query should have 2 active users but only shows 1
expect(electricCollection.status).toBe(`ready`)
expect(electricCollection.size).toBe(3)
expect(activeLiveQuery.status).toBe(`ready`)
expect(activeLiveQuery.size).toBe(2) // Only active users (Alice Updated and Eve)
})
it(`should handle must-refetch with complex projections`, () => {
const complexLiveQuery = createLiveQueryCollection({
startSync: true,
query: (q) =>
q
.from({ user: electricCollection })
.where(({ user }) => gt(user.age, 18))
.select(({ user }) => ({
userId: user.id,
displayName: user.name,
isAdult: user.age,
})),
})
// Initial sync and must-refetch
simulateInitialSync()
simulateMustRefetch()
const newUsers = [
{
id: 9,
name: `Iris`,
age: 30,
email: `iris@example.com`,
active: false,
},
{
id: 10,
name: `Jack`,
age: 17,
email: `jack@example.com`,
active: true,
}, // Under 18, filtered
]
simulateResync(newUsers)
expect(complexLiveQuery.status).toBe(`ready`)
expect(complexLiveQuery.size).toBe(1) // Only Iris (Jack filtered by age)
expect(complexLiveQuery.get(9)).toMatchObject({
userId: 9,
displayName: `Iris`,
isAdult: 30,
})
})
it(`should handle rapid must-refetch sequences`, () => {
const liveQuery = createLiveQueryCollection({
startSync: true,
query: (q) => q.from({ user: electricCollection }),
})
// Initial sync
simulateInitialSync()
expect(liveQuery.size).toBe(4)
// Multiple rapid must-refetch messages
simulateMustRefetch()
simulateMustRefetch()
simulateMustRefetch()
// Final resync
const newUsers = [
{
id: 10,
name: `New User`,
age: 20,
email: `new@example.com`,
active: true,
},
]
simulateResync(newUsers)
expect(electricCollection.status).toBe(`ready`)
expect(liveQuery.status).toBe(`ready`)
expect(liveQuery.size).toBe(1)
})
it(`should handle live query becoming ready after must-refetch during initial sync`, () => {
// Test that live queries properly transition to ready state when must-refetch
// occurs during the initial sync of the source Electric collection
let testSubscriber: (messages: Array<Message<User>>) => void
vi.clearAllMocks()
mockSubscribe.mockImplementation((callback) => {
testSubscriber = callback
return () => {}
})
// Create Electric collection
const testElectricCollection = createCollection(
electricCollectionOptions({
id: `initial-sync-collection`,
shapeOptions: {
url: `http://test-url`,
params: {
table: `users`,
},
},
startSync: true,
getKey: (user: User) => user.id,
autoIndex,
})
)
// Send initial data but don't complete sync (no up-to-date)
testSubscriber([
{
key: `1`,
value: {
id: 1,
name: `Alice`,
age: 25,
email: `alice@example.com`,
active: true,
},
headers: { operation: `insert` },
},
])
expect(testElectricCollection.status).toBe(`loading`)
// Create live query while Electric collection is still loading
const liveQuery = createLiveQueryCollection({
startSync: true,
query: (q) => q.from({ user: testElectricCollection }),
})
expect(liveQuery.status).toBe(`loading`)
// Send must-refetch while collection is in loading state
testSubscriber([{ headers: { control: `must-refetch` } }])
// Complete the sync
testSubscriber([{ headers: { control: `up-to-date` } }])
// Both Electric collection and live query should be ready
expect(testElectricCollection.status).toBe(`ready`)
expect(liveQuery.status).toBe(`ready`) // This currently fails - live query stuck in loading
})
})