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

query.e2e.test.ts

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