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

README.md

489 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({ post: postsCollection }, ({ user, post }) =>
334 eq(user.id, post.userId),
335 )
336 .select(({ user, post }) => ({
337 id: post.id,
338 userName: user.name,
339 postTitle: post.title,
340 })),
341 )
342 await query.preload()
343​
344 expect(query.size).toBeGreaterThan(0)
345})
346```
347​
348**Covers:**
349​
350- Two-collection joins (Users + Posts)
351- Three-collection joins (Users + Posts + Comments)
352- Mixed syncModes (eager + on-demand)
353- Predicates on joined collections
354- Left joins and ordering on joined results
355- Pagination on joined results
356​
357### Deduplication Suite
358​
359Tests concurrent loadSubset calls:
360​
361- Identical predicates called simultaneously
362- Overlapping predicates (subset relationships)
363- Queries during active loading
364- Deduplication callback verification
365​
366### Collation Suite
367​
368Tests string collation:
369​
370- Default collation behavior
371- Custom `defaultStringCollation`
372- Query-level collation override
373- Case-sensitive vs case-insensitive
374​
375### Mutations Suite
376​
377Tests data mutations:
378​
379- Insert, update, delete operations
380- Soft delete pattern
381- Concurrent mutations
382- Reactive query updates
383​
384### Live Updates Suite (Optional)
385​
386Tests reactive updates (for sync-enabled collections):
387​
388- Backend data changes
389- Updates during loadSubset
390- Multiple watchers
391- Subscription lifecycle
392​
393### Regression Suite
394​
395Tests for known bugs:
396​
397- Initial state sent multiple times (#7214245)
398- Race conditions in multi-join
399- Missing data in change tracking
400- LoadSubset naming changes (#9874949)
401​
402## Configuration
403​
404### Environment Variables
405​
406- `ELECTRIC_URL` - Electric server URL (default: `http://localhost:3000`)
407- `POSTGRES_HOST` - Postgres host (default: `localhost`)
408- `POSTGRES_PORT` - Postgres port (default: `54321`)
409- `POSTGRES_USER` - Postgres user (default: `postgres`)
410- `POSTGRES_PASSWORD` - Postgres password (default: `password`)
411- `POSTGRES_DB` - Postgres database (default: `e2e_test`)
412​
413### Docker Configuration
414​
415The Docker Compose setup uses:
416​
417- Postgres 16 Alpine with tmpfs for speed
418- Electric canary image
419- Health checks with 10s timeout
420- Optimized postgres.conf for testing
421​
422## Troubleshooting
423​
424### Docker services not starting
425​
426```bash
427# Check service status
428docker compose ps
429​
430# View logs
431docker compose logs
432​
433# Restart services
434docker compose restart
435```
436​
437### Tests timing out
438​
439- Increase `timeout` in `vite.config.ts`
440- Check Docker resource limits
441- Verify network connectivity
442​
443### Database connection errors
444​
445- Ensure Docker services are healthy
446- Check environment variables
447- Verify ports are not in use
448​
449### Test isolation issues
450​
451Tests use unique table names per test to prevent collisions:
452​
453```
454"users_taskId_random"
455```
456​
457If you see data from other tests, check that cleanup is working properly.
458​
459## Performance
460​
461Target execution time: **< 5 minutes** for entire suite
462​
463Optimizations:
464​
465- tmpfs for Postgres data directory
466- Serial execution (`fileParallelism: false`)
467- Minimal test data (~300 records total)
468- Optimized Postgres configuration
469- Health checks with fast intervals
470​
471## Contributing
472​
473When adding new test suites:
474​
4751. Create new file in `src/suites/`
4762. Export test factory function
4773. Add to main exports in `src/index.ts`
4784. Update README with test suite description
4795. Ensure execution time stays < 5 minutes
480​
481## License
482​
483MIT
484​
485## Related
486​
487- [RFC #676](https://github.com/TanStack/db/discussions/676) - Query-driven sync RFC
488- [PR #763](https://github.com/TanStack/db/pull/763) - Implementation PR
489- [TanStack DB Documentation](https://tanstack.com/db)