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

README.md

491 lines11.2 KB

1# @tanstack/db-collection-e2e
2​
3Shared end-to-end test suite for TanStack DB collections with query-driven sync and on-demand loading.
4​
5## Overview
6​
7This package provides a comprehensive e2e test suite that can be reused across different collection implementations (Electric, Query, etc.). It tests:
8​
9- Predicate push-down and filtering
10- Pagination, ordering, and window management
11- Multi-collection joins with mixed syncModes
12- Deduplication of concurrent loadSubset calls
13- String collation configurations
14- Mutations with on-demand mode
15- Live updates (for sync-enabled collections)
16​
17## Architecture
18​
19### Package Structure
20​
21```
22db-collection-e2e/
23├── docker/ # Docker Compose for test infrastructure
24│ ├── docker-compose.yml # Postgres + Electric
25│ └── postgres.conf # Optimized for fast tests
26├── src/
27│ ├── types.ts # TypeScript interfaces
28│ ├── fixtures/ # Test data and schemas
29│ │ ├── seed-data.ts # Generate ~100 records per table
30│ │ └── test-schema.ts # SQL schema definitions
31│ ├── suites/ # Test suite modules
32│ │ ├── predicates.test.ts
33│ │ ├── pagination.test.ts
34│ │ ├── joins.test.ts
35│ │ ├── deduplication.test.ts
36│ │ ├── collation.test.ts
37│ │ ├── mutations.test.ts
38│ │ ├── live-updates.test.ts
39│ │ └── regressions.test.ts
40│ └── utils/ # Helper functions
41│ ├── helpers.ts # Common utilities
42│ └── assertions.ts # Custom assertions
43└── support/ # Vitest setup
44 ├── global-setup.ts # Health checks, DB init
45 └── test-context.ts # Vitest fixtures
46```
47​
48## Getting Started
49​
50### Prerequisites
51​
52- Docker and Docker Compose
53- Node.js 20+
54- pnpm 10+
55​
56### Installation
57​
58From the repository root:
59​
60```bash
61pnpm install
62```
63​
64### Running Tests Locally
65​
661. **Start Docker services:**
67​
68```bash
69cd packages/db-collection-e2e/docker
70docker compose up -d
71```
72​
732. **Run tests:**
74​
75```bash
76cd packages/db-collection-e2e
77pnpm test
78```
79​
803. **Stop Docker services:**
81​
82```bash
83cd packages/db-collection-e2e/docker
84docker compose down
85```
86​
87## Test Data Schema
88​
89The test suite uses three related tables:
90​
91### Users Table (~100 records)
92​
93```typescript
94interface User {
95 id: string // UUID
96 name: string // For collation testing
97 email: string | null
98 age: number
99 isActive: boolean
100 createdAt: Date
101 metadata: object | null // JSON field
102 deletedAt: Date | null // Soft delete
104```
105​
106### Posts Table (~100 records)
107​
108```typescript
109interface Post {
110 id: string
111 userId: string // FK to User
112 title: string
113 content: string | null
114 viewCount: number
115 publishedAt: Date | null
116 deletedAt: Date | null
118```
119​
120### Comments Table (~100 records)
121​
122```typescript
123interface Comment {
124 id: string
125 postId: string // FK to Post
126 userId: string // FK to User
127 text: string
128 createdAt: Date
129 deletedAt: Date | null
131```
132​
133### Data Distributions
134​
135Seed data includes:
136​
137- Mix of null/non-null values
138- Various string cases (uppercase, lowercase, special chars)
139- Date ranges (past, present, future)
140- Numeric ranges (negative, zero, positive)
141- Some soft-deleted records (~10%)
142​
143## Integrating with Your Collection
144​
145### 1. Create Setup File
146​
147Create `e2e/setup.ts` in your collection package. See real examples:
148​
149- Electric: `packages/electric-db-collection/e2e/setup.ts`
150- Query: `packages/query-db-collection/e2e/setup.ts`
151​
152Example structure:
153​
154```typescript
155import { createCollection } from '@tanstack/db'
156import { yourCollectionOptions } from '../src'
157import type {
158 E2ETestConfig,
159 User,
160 Post,
161 Comment,
162} from '../../db-collection-e2e/src/types'
163​
164export async function createYourE2EConfig(options: {
165 schema: string
166 usersTable: string
167 postsTable: string
168 commentsTable: string
169}): Promise<E2ETestConfig> {
170 // Create collections for both syncModes (eager and on-demand)
171 const eagerUsers = createCollection(
172 yourCollectionOptions({
173 id: `your-e2e-users-eager-${Date.now()}`,
174 syncMode: 'eager',
175 getKey: (item: User) => item.id,
176 startSync: false,
177 }),
178 )
179​
180 const onDemandUsers = createCollection(
181 yourCollectionOptions({
182 id: `your-e2e-users-ondemand-${Date.now()}`,
183 syncMode: 'on-demand',
184 getKey: (item: User) => item.id,
185 startSync: false,
186 }),
187 )
188​
189 // ... create posts and comments collections similarly
190​
191 return {
192 collections: {
193 eager: { users: eagerUsers, posts: eagerPosts, comments: eagerComments },
194 onDemand: {
195 users: onDemandUsers,
196 posts: onDemandPosts,
197 comments: onDemandComments,
198 },
199 },
200 setup: async () => {
201 // Optional setup hook
202 },
203 teardown: async () => {
204 await Promise.all([
205 eagerUsers.cleanup(),
206 eagerPosts.cleanup(),
207 eagerComments.cleanup(),
208 onDemandUsers.cleanup(),
209 onDemandPosts.cleanup(),
210 onDemandComments.cleanup(),
211 ])
212 },
213 }
215```
216​
217### 2. Create E2E Test File
218​
219Create `e2e/your-collection.e2e.test.ts`:
220​
221```typescript
222import { describe, it, expect } from 'vitest'
223import { createCollection } from '@tanstack/db'
224import { yourCollectionOptions } from '../src'
225​
226describe('Your Collection E2E', () => {
227 it('should create collection', async () => {
228 const collection = createCollection(
229 yourCollectionOptions({
230 id: 'test-collection',
231 getKey: (item: any) => item.id,
232 startSync: false,
233 }),
234 )
235​
236 expect(collection).toBeDefined()
237 expect(collection._sync.loadSubset).toBeDefined()
238​
239 await collection.cleanup()
240 })
241})
242```
243​
244### 3. Update Vitest Config
245​
246Update your `vite.config.ts` to include e2e tests:
247​
248```typescript
249const config = defineConfig({
250 test: {
251 include: ['tests/**/*.test.ts', 'e2e/**/*.e2e.test.ts'],
252 // Remove dir: './tests' if present
253 },
254})
255```
256​
257### 4. Run Tests
258​
259```bash
260cd packages/your-collection
261pnpm test
262```
263​
264The e2e tests will run alongside your regular tests.
265​
266## Test Suites
267​
268All test suites are implemented in `src/suites/*.suite.ts` files and exported as factory functions.
269​
270### Predicates Suite (`predicates-oracle.suite.ts`)
271​
272Tests basic where clause functionality with ~20 test scenarios:
273​
274**Example Test:**
275​
276```typescript
277it('should filter with eq() on number field', async () => {
278 const query = createLiveQueryCollection((q) =>
279 q.from({ user: usersCollection }).where(({ user }) => eq(user.age, 25)),
280 )
281 await query.preload()
282​
283 const results = Array.from(query.state.values())
284 assertAllItemsMatch(query, (u) => u.age === 25)
285})
286```
287​
288**Covers:**
289​
290- `eq()`, `gt()`, `gte()`, `lt()`, `lte()` with all data types
291- `inArray()` with arrays
292- `isNull()`, `not(isNull())` for null checks
293- Complex boolean logic with `and()`, `or()`, `not()`
294- Predicate pushdown verification
295​
296### Pagination Suite (`pagination-oracle.suite.ts`)
297​
298Tests ordering and pagination with ~15 test scenarios:
299​
300**Example Test:**
301​
302```typescript
303it('should sort ascending by single field', async () => {
304 const query = createLiveQueryCollection((q) =>
305 q.from({ user: usersCollection }).orderBy(({ user }) => user.age, 'asc'),
306 )
307 await query.preload()
308​
309 const results = Array.from(query.state.values())
310 assertSorted(results, 'age', 'asc')
311})
312```
313​
314**Covers:**
315​
316- Basic `orderBy` (asc/desc) on various field types
317- Multiple `orderBy` fields
318- `limit` and `offset` for pagination
319- Edge cases (limit=0, offset beyond dataset)
320- Performance verification (only requested page loaded)
321​
322### Joins Suite (`joins-oracle.suite.ts`)
323​
324Tests multi-collection joins with ~12 test scenarios:
325​
326**Example Test:**
327​
328```typescript
329it('should join Users and Posts', async () => {
330 const query = createLiveQueryCollection((q) =>
331 q
332 .from({ user: usersCollection })
333 .join(
334 leftJoin({ post: postsCollection }, ({ user, post }) =>
335 eq(user.id, post.userId),
336 ),
337 )
338 .select(({ user, post }) => ({
339 id: post.id,
340 userName: user.name,
341 postTitle: post.title,
342 })),
343 )
344 await query.preload()
345​
346 expect(query.size).toBeGreaterThan(0)
347})
348```
349​
350**Covers:**
351​
352- Two-collection joins (Users + Posts)
353- Three-collection joins (Users + Posts + Comments)
354- Mixed syncModes (eager + on-demand)
355- Predicates on joined collections
356- Left joins and ordering on joined results
357- Pagination on joined results
358​
359### Deduplication Suite
360​
361Tests concurrent loadSubset calls:
362​
363- Identical predicates called simultaneously
364- Overlapping predicates (subset relationships)
365- Queries during active loading
366- Deduplication callback verification
367​
368### Collation Suite
369​
370Tests string collation:
371​
372- Default collation behavior
373- Custom `defaultStringCollation`
374- Query-level collation override
375- Case-sensitive vs case-insensitive
376​
377### Mutations Suite
378​
379Tests data mutations:
380​
381- Insert, update, delete operations
382- Soft delete pattern
383- Concurrent mutations
384- Reactive query updates
385​
386### Live Updates Suite (Optional)
387​
388Tests reactive updates (for sync-enabled collections):
389​
390- Backend data changes
391- Updates during loadSubset
392- Multiple watchers
393- Subscription lifecycle
394​
395### Regression Suite
396​
397Tests for known bugs:
398​
399- Initial state sent multiple times (#7214245)
400- Race conditions in multi-join
401- Missing data in change tracking
402- LoadSubset naming changes (#9874949)
403​
404## Configuration
405​
406### Environment Variables
407​
408- `ELECTRIC_URL` - Electric server URL (default: `http://localhost:3000`)
409- `POSTGRES_HOST` - Postgres host (default: `localhost`)
410- `POSTGRES_PORT` - Postgres port (default: `54321`)
411- `POSTGRES_USER` - Postgres user (default: `postgres`)
412- `POSTGRES_PASSWORD` - Postgres password (default: `password`)
413- `POSTGRES_DB` - Postgres database (default: `e2e_test`)
414​
415### Docker Configuration
416​
417The Docker Compose setup uses:
418​
419- Postgres 16 Alpine with tmpfs for speed
420- Electric canary image
421- Health checks with 10s timeout
422- Optimized postgres.conf for testing
423​
424## Troubleshooting
425​
426### Docker services not starting
427​
428```bash
429# Check service status
430docker compose ps
431​
432# View logs
433docker compose logs
434​
435# Restart services
436docker compose restart
437```
438​
439### Tests timing out
440​
441- Increase `timeout` in `vite.config.ts`
442- Check Docker resource limits
443- Verify network connectivity
444​
445### Database connection errors
446​
447- Ensure Docker services are healthy
448- Check environment variables
449- Verify ports are not in use
450​
451### Test isolation issues
452​
453Tests use unique table names per test to prevent collisions:
454​
455```
456"users_taskId_random"
457```
458​
459If you see data from other tests, check that cleanup is working properly.
460​
461## Performance
462​
463Target execution time: **< 5 minutes** for entire suite
464​
465Optimizations:
466​
467- tmpfs for Postgres data directory
468- Serial execution (`fileParallelism: false`)
469- Minimal test data (~300 records total)
470- Optimized Postgres configuration
471- Health checks with fast intervals
472​
473## Contributing
474​
475When adding new test suites:
476​
4771. Create new file in `src/suites/`
4782. Export test factory function
4793. Add to main exports in `src/index.ts`
4804. Update README with test suite description
4815. Ensure execution time stays < 5 minutes
482​
483## License
484​
485MIT
486​
487## Related
488​
489- [RFC #676](https://github.com/TanStack/db/discussions/676) - Query-driven sync RFC
490- [PR #763](https://github.com/TanStack/db/pull/763) - Implementation PR
491- [TanStack DB Documentation](https://tanstack.com/db)