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

query.e2e.test.ts

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