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

query.e2e.test.ts

276 lines8.8 KB

1/**
2 * Query Collection E2E Tests
3 *
4 * Tests using Query collections with mock backend
5 */
6​
7import { afterAll, afterEach, beforeAll, describe } from 'vitest'
8import { BTreeIndex, createCollection } from '@tanstack/db'
9import { QueryClient } from '@tanstack/query-core'
10import { queryCollectionOptions } from '../src/query'
11import {
12 captureSeedData,
13 createCollationTestSuite,
14 createDeduplicationTestSuite,
15 createJoinsTestSuite,
16 createLiveUpdatesTestSuite,
17 createMutationsTestSuite,
18 createPaginationTestSuite,
19 createPredicatesTestSuite,
20 generateSeedData,
21} from '../../db-collection-e2e/src/index'
22import { applyPredicates, buildQueryKey } from './query-filter'
23import type {
24 Comment as E2EComment,
25 Post as E2EPost,
26 E2ETestConfig,
27 User as E2EUser,
28} from '../../db-collection-e2e/src/types'
29​
30describe(`Query Collection E2E Tests`, () => {
31 let config: E2ETestConfig
32 let queryClient: QueryClient
33​
34 beforeAll(async () => {
35 const fixture = captureSeedData(generateSeedData(), {
36 registration: 'packages/query-db-collection/e2e/query.e2e.test.ts',
37 provider: 'QueryClient with finite in-memory backend',
38 })
39 // Backend writes never modify the independently retained initial authority.
40 const seedData = fixture()
41​
42 queryClient = new QueryClient({
43 defaultOptions: {
44 queries: {
45 staleTime: 0,
46 retry: false,
47 },
48 },
49 })
50​
51 // Create REAL Query collections with mock backend queryFn
52 const eagerUsers = createCollection(
53 queryCollectionOptions({
54 id: `query-e2e-users-eager`,
55 queryClient,
56 queryKey: [`e2e`, `users`, `eager`],
57 queryFn: () => {
58 // Mock query function that returns seed data
59 return Promise.resolve(structuredClone(seedData.users))
60 },
61 getKey: (item: E2EUser) => item.id,
62 startSync: true,
63 autoIndex: `eager`,
64 defaultIndexType: BTreeIndex,
65 }),
66 )
67​
68 const eagerPosts = createCollection(
69 queryCollectionOptions({
70 id: `query-e2e-posts-eager`,
71 queryClient,
72 queryKey: [`e2e`, `posts`, `eager`],
73 queryFn: () => {
74 return Promise.resolve(structuredClone(seedData.posts))
75 },
76 getKey: (item: E2EPost) => item.id,
77 startSync: true,
78 autoIndex: `eager`,
79 defaultIndexType: BTreeIndex,
80 }),
81 )
82​
83 const eagerComments = createCollection(
84 queryCollectionOptions({
85 id: `query-e2e-comments-eager`,
86 queryClient,
87 queryKey: [`e2e`, `comments`, `eager`],
88 queryFn: () => {
89 return Promise.resolve(structuredClone(seedData.comments))
90 },
91 getKey: (item: E2EComment) => item.id,
92 startSync: true,
93 autoIndex: `eager`,
94 defaultIndexType: BTreeIndex,
95 }),
96 )
97​
98 const onDemandUsers = createCollection(
99 queryCollectionOptions({
100 id: `query-e2e-users-ondemand`,
101 queryClient,
102 // Function-based queryKey that derives a serializable key from predicate options
103 // This ensures different predicates create separate TanStack Query observers
104 queryKey: (opts) => buildQueryKey(`users`, opts),
105 syncMode: `on-demand`,
106 queryFn: (ctx) => {
107 const options = ctx.meta?.loadSubsetOptions
108 const filtered = applyPredicates(seedData.users, options)
109 return Promise.resolve(structuredClone(filtered))
110 },
111 getKey: (item: E2EUser) => item.id,
112 startSync: false,
113 autoIndex: `eager`,
114 defaultIndexType: BTreeIndex,
115 }),
116 )
117​
118 const onDemandPosts = createCollection(
119 queryCollectionOptions({
120 id: `query-e2e-posts-ondemand`,
121 queryClient,
122 queryKey: (opts) => buildQueryKey(`posts`, opts),
123 syncMode: `on-demand`,
124 queryFn: (ctx) => {
125 const options = ctx.meta?.loadSubsetOptions
126 const filtered = applyPredicates(seedData.posts, options)
127 return Promise.resolve(structuredClone(filtered))
128 },
129 getKey: (item: E2EPost) => item.id,
130 startSync: false,
131 autoIndex: `eager`,
132 defaultIndexType: BTreeIndex,
133 }),
134 )
135​
136 const onDemandComments = createCollection(
137 queryCollectionOptions({
138 id: `query-e2e-comments-ondemand`,
139 queryClient,
140 queryKey: (opts) => buildQueryKey(`comments`, opts),
141 syncMode: `on-demand`,
142 queryFn: (ctx) => {
143 const options = ctx.meta?.loadSubsetOptions
144 const filtered = applyPredicates(seedData.comments, options)
145 return Promise.resolve(structuredClone(filtered))
146 },
147 getKey: (item: E2EComment) => item.id,
148 startSync: false,
149 autoIndex: `eager`,
150 defaultIndexType: BTreeIndex,
151 }),
152 )
153​
154 // Wait for eager collections to load
155 await eagerUsers.preload()
156 await eagerPosts.preload()
157 await eagerComments.preload()
158​
159 // On-demand collections don't start automatically
160 await onDemandUsers.preload()
161 await onDemandPosts.preload()
162 await onDemandComments.preload()
163​
164 config = {
165 fixture,
166 collections: {
167 eager: {
168 users: eagerUsers as any,
169 posts: eagerPosts as any,
170 comments: eagerComments as any,
171 },
172 onDemand: {
173 users: onDemandUsers as any,
174 posts: onDemandPosts as any,
175 comments: onDemandComments as any,
176 },
177 },
178 // Mutations for Query collections - modify seed data and invalidate queries
179 mutations: {
180 insertUser: async (user) => {
181 console.log(`[mutation] insertUser called, id=${user.id}`)
182 seedData.users.push(structuredClone(user))
183 console.log(`[mutation] calling invalidateQueries`)
184 await queryClient.invalidateQueries({ queryKey: [`e2e`, `users`] })
185 console.log(`[mutation] invalidateQueries completed`)
186 },
187 updateUser: async (id, updates) => {
188 console.log(`[mutation] updateUser called, id=${id}`)
189 const userIndex = seedData.users.findIndex((u) => u.id === id)
190 if (userIndex !== -1) {
191 seedData.users[userIndex] = {
192 ...seedData.users[userIndex]!,
193 ...structuredClone(updates),
194 }
195 console.log(`[mutation] calling invalidateQueries`)
196 await queryClient.invalidateQueries({ queryKey: [`e2e`, `users`] })
197 console.log(`[mutation] invalidateQueries completed`)
198 }
199 },
200 deleteUser: async (id) => {
201 console.log(`[mutation] deleteUser called, id=${id}`)
202 const userIndex = seedData.users.findIndex((u) => u.id === id)
203 if (userIndex !== -1) {
204 seedData.users.splice(userIndex, 1)
205 console.log(`[mutation] calling invalidateQueries`)
206 await queryClient.invalidateQueries({ queryKey: [`e2e`, `users`] })
207 console.log(`[mutation] invalidateQueries completed`)
208 }
209 },
210 insertPost: async (post) => {
211 seedData.posts.push(structuredClone(post))
212 await queryClient.invalidateQueries({ queryKey: [`e2e`, `posts`] })
213 },
214 deletePost: async (id) => {
215 const postIndex = seedData.posts.findIndex((post) => post.id === id)
216 if (postIndex !== -1) {
217 seedData.posts.splice(postIndex, 1)
218 await queryClient.invalidateQueries({ queryKey: [`e2e`, `posts`] })
219 }
220 },
221 },
222 setup: async () => {},
223 afterEach: async () => {
224 // Clean up and restart on-demand collections
225 // This validates cleanup() works and each test starts fresh
226 await onDemandUsers.cleanup()
227 await onDemandPosts.cleanup()
228 await onDemandComments.cleanup()
229​
230 // Restart sync after cleanup
231 onDemandUsers.startSyncImmediate()
232 onDemandPosts.startSyncImmediate()
233 onDemandComments.startSyncImmediate()
234​
235 // Wait for collections to be ready
236 await onDemandUsers.preload()
237 await onDemandPosts.preload()
238 await onDemandComments.preload()
239 },
240 teardown: async () => {
241 await Promise.all([
242 eagerUsers.cleanup(),
243 eagerPosts.cleanup(),
244 eagerComments.cleanup(),
245 onDemandUsers.cleanup(),
246 onDemandPosts.cleanup(),
247 onDemandComments.cleanup(),
248 ])
249 queryClient.clear()
250 },
251 }
252 })
253​
254 afterEach(async () => {
255 if (config.afterEach) {
256 await config.afterEach()
257 }
258 })
259​
260 afterAll(async () => {
261 await config.teardown()
262 })
263​
264 function getConfig() {
265 return Promise.resolve(config)
266 }
267​
268 // Run all test suites
269 createPredicatesTestSuite(getConfig)
270 createPaginationTestSuite(getConfig)
271 createJoinsTestSuite(getConfig)
272 createDeduplicationTestSuite(getConfig)
273 createCollationTestSuite(getConfig)
274 createMutationsTestSuite(getConfig)
275 createLiveUpdatesTestSuite(getConfig)
276})