e2e-test-scenarios
Instructions
This skill provides comprehensive end-to-end testing capabilities for Supabase applications, covering database operations, authentication flows, AI features (pgvector), realtime subscriptions, and production readiness validation.
Phase 1: Setup Test Environment
Initialize test environment:
bash scripts/setup-test-env.sh
This creates:
- Test database configuration
- Environment variables for testing
- Test data fixtures
- CI/CD configuration templates
Configure test database:
- Use dedicated test project or local Supabase instance
- Never run tests against production
- Set
SUPABASE_TEST_URL and SUPABASE_TEST_ANON_KEY
- Enable pgTAP extension for database tests
Install dependencies:
npm install --save-dev @supabase/supabase-js jest @types/jest
# or
pnpm add -D @supabase/supabase-js vitest
Phase 2: Database Workflow Testing
Test complete database operations from schema to queries:
Run database E2E tests:
bash scripts/test-database-workflow.sh
This validates:
- Schema creation and migrations
- Table relationships and foreign keys
- RLS policies enforcement
- Triggers and functions
- Data integrity constraints
Use pgTAP for SQL-level tests:
# Run all database tests
supabase test db
# Run specific test file
supabase test db --file tests/database/users.test.sql
Test schema migrations:
# Test migration up/down
supabase db reset --linked
supabase db push
# Verify schema state
bash scripts/validate-schema.sh
Phase 3: Authentication Flow Testing
Test complete auth workflows end-to-end:
Run authentication E2E tests:
bash scripts/test-auth-workflow.sh
This validates:
- Email/password signup and login
- Magic link authentication
- OAuth provider flows (Google, GitHub, etc.)
- Session management and refresh
- Password reset flows
- Email verification
- Multi-factor authentication (MFA)
Test RLS with authenticated users:
// See templates/auth-tests.ts for complete examples
test('authenticated users see only their data', async () => {
const { data, error } = await supabase
.from('private_notes')
.select('*');
expect(data).toHaveLength(userNoteCount);
expect(data.every(note => note.user_id === userId)).toBe(true);
});
Test session persistence:
# Run session validation tests
npm test -- auth-session.test.ts
Phase 4: AI Features Testing (pgvector)
Test vector search and semantic operations:
Run AI features E2E tests:
bash scripts/test-ai-features.sh
This validates:
- pgvector extension is enabled
- Embedding storage and retrieval
- Vector similarity search accuracy
- HNSW/IVFFlat index performance
- Hybrid search (keyword + semantic)
- Embedding dimension consistency
Test vector search accuracy:
// See templates/vector-search-tests.ts
test('semantic search returns relevant results', async () => {
const queryEmbedding = await generateEmbedding('machine learning');
const { data } = await supabase.rpc('match_documents', {
query_embedding: queryEmbedding
match_threshold: 0.7
match_count: 5
});
expect(data.length).toBeGreaterThan(0);
expect(data[0].similarity).toBeGreaterThan(0.7);
});
Test embedding operations:
# Validate embedding pipeline
npm test -- embedding-workflow.test.ts
Performance benchmarking:
# Run performance tests
bash scripts/benchmark-vector-search.sh [TABLE_NAME] [VECTOR_DIM]
Phase 5: Realtime Features Testing
Test realtime subscriptions and presence:
Run realtime E2E tests:
bash scripts/test-realtime-workflow.sh
This validates:
- Database change subscriptions
- Broadcast messaging
- Presence tracking
- Connection handling
- Reconnection logic
- Subscription cleanup
Test database change subscriptions:
// See templates/realtime-tests.ts
test('receives real-time updates on insert', async () => {
const updates = [];
const subscription = supabase
.channel('test-channel')
.on('postgres_changes'
{ event: 'INSERT', schema: 'public', table: 'messages' }
(payload) => updates.push(payload)
)
.subscribe();
await supabase.from('messages').insert({ content: 'test' });
await waitFor(() => expect(updates).toHaveLength(1));
});
Test presence and broadcast:
# Run presence tests
npm test -- presence.test.ts
Phase 6: Complete Integration Tests
Run full workflow tests simulating real user scenarios:
Execute complete E2E test suite:
bash scripts/run-e2e-tests.sh
This runs:
- User signup → profile creation → data CRUD → logout
- Document upload → embedding generation → semantic search
- Chat message → realtime delivery → read receipts
- Multi-user collaboration scenarios
- Error handling and recovery
Run test scenarios in parallel:
# Run all test suites
npm test -- --maxWorkers=4
# Run specific workflow
npm test -- workflows/document-rag.test.ts
Generate test reports:
# Generate coverage report
npm test -- --coverage
# Generate HTML report
npm test -- --coverage --coverageReporters=html
Phase 7: CI/CD Integration
Setup automated testing in CI/CD pipelines:
Use GitHub Actions template:
# Copy CI config to your repo
cp templates/ci-config.yml .github/workflows/supabase-tests.yml
Configure test secrets:
- Add
SUPABASE_TEST_URL to GitHub secrets
- Add
SUPABASE_TEST_ANON_KEY to GitHub secrets
- Add
SUPABASE_TEST_SERVICE_ROLE_KEY for admin tests
Run tests on pull requests:
- Automatic test execution on PR creation
- Blocking PRs if tests fail
- Test result reporting in PR comments
Phase 8: Cleanup and Teardown
Clean up test resources after testing:
Run cleanup script:
bash scripts/cleanup-test-resources.sh
This removes:
- Test users and sessions
- Test data from tables
- Temporary test databases
- Test file uploads
Reset test database:
# Reset to clean state
supabase db reset --linked
# Or use migration-based reset
bash scripts/reset-test-db.sh
Test Coverage Areas
Database Testing
- Schema Validation: Table structure, columns, constraints
- Migration Testing: Up/down migrations, rollback safety
- RLS Policies: Access control, policy enforcement
- Functions & Triggers: Database logic, event handlers
- Performance: Query optimization, index usage
Authentication Testing
- User Flows: Signup, login, logout, password reset
- Provider Integration: OAuth, magic links, phone auth
- Session Management: Token refresh, expiration, persistence
- MFA: Setup, verification, recovery codes
- Security: Rate limiting, brute force protection
AI Features Testing
- Vector Operations: Insert, update, delete embeddings
- Similarity Search: Accuracy, relevance, threshold tuning
- Index Performance: HNSW vs IVFFlat, query speed
- Hybrid Search: Combined keyword and semantic search
- Dimension Validation: Embedding size consistency
Realtime Testing
- Subscriptions: Database changes, broadcasts, presence
- Connection Management: Connect, disconnect, reconnect
- Message Delivery: Ordering, reliability, deduplication
- Performance: Latency, throughput, concurrent users
- Cleanup: Subscription disposal, memory leaks
Integration Testing
- Multi-Component: Auth + Database + Storage
- User Journeys: Complete workflows end-to-end
- Error Scenarios: Network failures, invalid data, rate limits
- Edge Cases: Concurrent updates, race conditions, timeouts
Test Data Strategies
Fixture Management
// Load test fixtures
const testData = await loadFixtures('users', 'posts', 'comments');
// Seed database
await seedDatabase(testData);
// Cleanup after tests
afterAll(async () => {
await cleanupFixtures();
});
Factory Patterns
// Create test users with factories
const user = await createTestUser({
email: 'test@example.com'
metadata: { role: 'admin' }
});
// Create related data
const posts = await createTestPosts(user.id, 5);
Isolation Strategies
- Test Database: Dedicated test project
- Transaction Rollback: Rollback after each test
- Namespace Prefixes:
test_ prefix for test data
- Time-based Cleanup: Delete data older than X hours
Performance Benchmarks
Query Performance Targets
- Simple queries: < 50ms
- Vector similarity search: < 100ms
- Hybrid search: < 200ms
- Complex joins: < 300ms
Realtime Latency Targets
- Message delivery: < 100ms
- Presence updates: < 200ms
- Database changes: < 500ms
Throughput Targets
- Authenticated requests: 100+ req/s
- Vector searches: 50+ req/s
- Realtime messages: 1000+ msg/s
Common Test Patterns
Pattern 1: Auth-Protected Resource Test
test('authenticated user CRUD operations', async () => {
// 1. Sign up user
const { user } = await supabase.auth.signUp({
email: 'test@example.com'
password: 'test123'
});
// 2. Create resource
const { data } = await supabase
.from('notes')
.insert({ content: 'test note' })
.select()
.single();
// 3. Verify ownership
expect(data.user_id).toBe(user.id);
// 4. Update resource
await supabase
.from('notes')
.update({ content: 'updated' })
.eq('id', data.id);
// 5. Delete resource
await supabase.from('notes').delete().eq('id', data.id);
});
Pattern 2: Vector Search Workflow Test
test('document RAG workflow', async () => {
// 1. Upload document
const doc = await uploadDocument('test.pdf');
// 2. Generate embeddings
const chunks = await chunkDocument(doc);
const embeddings = await generateEmbeddings(chunks);
// 3. Store in database
await supabase.from('document_chunks').insert(
chunks.map((chunk, i) => ({
content: chunk
embedding: embeddings[i]
document_id: doc.id
}))
);
// 4. Perform semantic search
const query = 'What is the main topic?';
const queryEmbedding = await generateEmbedding(query);
const { data } = await supabase.rpc('match_documents', {
query_embedding: queryEmbedding
match_count: 5
});
// 5. Verify results
expect(data.length).toBeGreaterThan(0);
expect(data[0].similarity).toBeGreaterThan(0.7);
});
Pattern 3: Realtime Collaboration Test
test('multi-user realtime chat', async () => {
// 1. Create two users
const user1 = await createTestUser();
const user2 = await createTestUser();
// 2. Subscribe to messages
const user1Messages = [];
const user2Messages = [];
const sub1 = await subscribeToMessages(user1, user1Messages);
const sub2 = await subscribeToMessages(user2, user2Messages);
// 3. User 1 sends message
await sendMessage(user1, 'Hello from user 1');
// 4. Verify both users receive it
await waitFor(() => {
expect(user1Messages).toHaveLength(1);
expect(user2Messages).toHaveLength(1);
});
// 5. Cleanup subscriptions
await sub1.unsubscribe();
await sub2.unsubscribe();
});
Troubleshooting
Tests Failing Intermittently
- Race Conditions: Add proper wait conditions
- Async Issues: Ensure all promises are awaited
- Cleanup: Verify test isolation and cleanup
- Timeouts: Increase timeout for slow operations
Tests Passing Locally but Failing in CI
- Environment: Verify env variables in CI
- Timing: CI may be slower, increase timeouts
- Parallelization: Check for shared state issues
- Dependencies: Ensure all deps are installed
Slow Test Execution
- Parallel Tests: Use
--maxWorkers flag
- Test Selection: Run only changed tests
- Database Reset: Use faster cleanup methods
- Mocking: Mock external services
Database Connection Issues
- Connection Pooling: Limit concurrent connections
- Cleanup: Properly close connections after tests
- Retries: Implement connection retry logic
- Timeouts: Set appropriate connection timeouts
Files Reference
Scripts:
scripts/setup-test-env.sh - Initialize test environment
scripts/run-e2e-tests.sh - Execute complete test suite
scripts/test-database-workflow.sh - Database E2E tests
scripts/test-auth-workflow.sh - Authentication E2E tests
scripts/test-ai-features.sh - Vector search E2E tests
scripts/test-realtime-workflow.sh - Realtime E2E tests
scripts/cleanup-test-resources.sh - Clean up test data
scripts/validate-schema.sh - Validate database schema
scripts/benchmark-vector-search.sh - Performance benchmarks
scripts/reset-test-db.sh - Reset test database
Templates:
templates/test-suite-template.ts - Jest/Vitest boilerplate
templates/database-tests.ts - Database operation tests
templates/auth-tests.ts - Authentication flow tests
templates/vector-search-tests.ts - pgvector tests
templates/realtime-tests.ts - Realtime subscription tests
templates/ci-config.yml - GitHub Actions CI/CD
templates/jest.config.js - Jest configuration
templates/vitest.config.ts - Vitest configuration
Examples:
examples/complete-test-workflow.md - Full E2E testing guide
examples/ci-cd-integration.md - CI/CD setup guide
examples/test-data-strategies.md - Test data management
examples/performance-benchmarks.md - Performance testing
examples/mocking-strategies.md - Mocking external services
Plugin: supabase
Version: 1.0.0
Last Updated: 2025-10-26
1---2name: e2e-test-scenarios3description: End-to-end testing scenarios for Supabase - complete workflow tests from project creation to AI features, validation scripts, and comprehensive test suites. Use when testing Supabase integrations, validating AI workflows, running E2E tests, verifying production readiness, or when user mentions Supabase testing, E2E tests, integration testing, pgvector testing, auth testing, or test automation.4---5
6# e2e-test-scenarios
7
8## Instructions
9
10This skill provides comprehensive end-to-end testing capabilities for Supabase applications, covering database operations, authentication flows, AI features (pgvector), realtime subscriptions, and production readiness validation.
11
12### Phase 1: Setup Test Environment
13
141. Initialize test environment:
15 ```bash
16 bash scripts/setup-test-env.sh
17 ```
18 This creates:
19 - Test database configuration
20 - Environment variables for testing
21 - Test data fixtures
22 - CI/CD configuration templates
23
242. Configure test database:
25 - Use dedicated test project or local Supabase instance
26 - Never run tests against production
27 - Set `SUPABASE_TEST_URL` and `SUPABASE_TEST_ANON_KEY`
28 - Enable pgTAP extension for database tests
29
303. Install dependencies:
31 ```bash
32 npm install --save-dev @supabase/supabase-js jest @types/jest
33 # or
34 pnpm add -D @supabase/supabase-js vitest
35 ```
36
37### Phase 2: Database Workflow Testing
38
39Test complete database operations from schema to queries:
40
411. Run database E2E tests:
42 ```bash
43 bash scripts/test-database-workflow.sh
44 ```
45
46 This validates:
47 - Schema creation and migrations
48 - Table relationships and foreign keys
49 - RLS policies enforcement
50 - Triggers and functions
51 - Data integrity constraints
52
532. Use pgTAP for SQL-level tests:
54 ```bash
55 # Run all database tests
56 supabase test db
57
58 # Run specific test file
59 supabase test db --file tests/database/users.test.sql
60 ```
61
623. Test schema migrations:
63 ```bash
64 # Test migration up/down
65 supabase db reset --linked
66 supabase db push
67
68 # Verify schema state
69 bash scripts/validate-schema.sh
70 ```
71
72### Phase 3: Authentication Flow Testing
73
74Test complete auth workflows end-to-end:
75
761. Run authentication E2E tests:
77 ```bash
78 bash scripts/test-auth-workflow.sh
79 ```
80
81 This validates:
82 - Email/password signup and login
83 - Magic link authentication
84 - OAuth provider flows (Google, GitHub, etc.)
85 - Session management and refresh
86 - Password reset flows
87 - Email verification
88 - Multi-factor authentication (MFA)
89
902. Test RLS with authenticated users:
91 ```typescript
92 // See templates/auth-tests.ts for complete examples
93 test('authenticated users see only their data', async () => {
94 const { data, error } = await supabase
95 .from('private_notes')
96 .select('*');
97
98 expect(data).toHaveLength(userNoteCount);
99 expect(data.every(note => note.user_id === userId)).toBe(true);
100 });
101 ```
102
1033. Test session persistence:
104 ```bash
105 # Run session validation tests
106 npm test -- auth-session.test.ts
107 ```
108
109### Phase 4: AI Features Testing (pgvector)
110
111Test vector search and semantic operations:
112
1131. Run AI features E2E tests:
114 ```bash
115 bash scripts/test-ai-features.sh
116 ```
117
118 This validates:
119 - pgvector extension is enabled
120 - Embedding storage and retrieval
121 - Vector similarity search accuracy
122 - HNSW/IVFFlat index performance
123 - Hybrid search (keyword + semantic)
124 - Embedding dimension consistency
125
1262. Test vector search accuracy:
127 ```typescript
128 // See templates/vector-search-tests.ts
129 test('semantic search returns relevant results', async () => {
130 const queryEmbedding = await generateEmbedding('machine learning');
131
132 const { data } = await supabase.rpc('match_documents', {
133 query_embedding: queryEmbedding
134 match_threshold: 0.7
135 match_count: 5
136 });
137
138 expect(data.length).toBeGreaterThan(0);
139 expect(data[0].similarity).toBeGreaterThan(0.7);
140 });
141 ```
142
1433. Test embedding operations:
144 ```bash
145 # Validate embedding pipeline
146 npm test -- embedding-workflow.test.ts
147 ```
148
1494. Performance benchmarking:
150 ```bash
151 # Run performance tests
152 bash scripts/benchmark-vector-search.sh [TABLE_NAME] [VECTOR_DIM]
153 ```
154
155### Phase 5: Realtime Features Testing
156
157Test realtime subscriptions and presence:
158
1591. Run realtime E2E tests:
160 ```bash
161 bash scripts/test-realtime-workflow.sh
162 ```
163
164 This validates:
165 - Database change subscriptions
166 - Broadcast messaging
167 - Presence tracking
168 - Connection handling
169 - Reconnection logic
170 - Subscription cleanup
171
1722. Test database change subscriptions:
173 ```typescript
174 // See templates/realtime-tests.ts
175 test('receives real-time updates on insert', async () => {
176 const updates = [];
177
178 const subscription = supabase
179 .channel('test-channel')
180 .on('postgres_changes'
181 { event: 'INSERT', schema: 'public', table: 'messages' }
182 (payload) => updates.push(payload)
183 )
184 .subscribe();
185
186 await supabase.from('messages').insert({ content: 'test' });
187
188 await waitFor(() => expect(updates).toHaveLength(1));
189 });
190 ```
191
1923. Test presence and broadcast:
193 ```bash
194 # Run presence tests
195 npm test -- presence.test.ts
196 ```
197
198### Phase 6: Complete Integration Tests
199
200Run full workflow tests simulating real user scenarios:
201
2021. Execute complete E2E test suite:
203 ```bash
204 bash scripts/run-e2e-tests.sh
205 ```
206
207 This runs:
208 - User signup → profile creation → data CRUD → logout
209 - Document upload → embedding generation → semantic search
210 - Chat message → realtime delivery → read receipts
211 - Multi-user collaboration scenarios
212 - Error handling and recovery
213
2142. Run test scenarios in parallel:
215 ```bash
216 # Run all test suites
217 npm test -- --maxWorkers=4
218
219 # Run specific workflow
220 npm test -- workflows/document-rag.test.ts
221 ```
222
2233. Generate test reports:
224 ```bash
225 # Generate coverage report
226 npm test -- --coverage
227
228 # Generate HTML report
229 npm test -- --coverage --coverageReporters=html
230 ```
231
232### Phase 7: CI/CD Integration
233
234Setup automated testing in CI/CD pipelines:
235
2361. Use GitHub Actions template:
237 ```bash
238 # Copy CI config to your repo
239 cp templates/ci-config.yml .github/workflows/supabase-tests.yml
240 ```
241
2422. Configure test secrets:
243 - Add `SUPABASE_TEST_URL` to GitHub secrets
244 - Add `SUPABASE_TEST_ANON_KEY` to GitHub secrets
245 - Add `SUPABASE_TEST_SERVICE_ROLE_KEY` for admin tests
246
2473. Run tests on pull requests:
248 - Automatic test execution on PR creation
249 - Blocking PRs if tests fail
250 - Test result reporting in PR comments
251
252### Phase 8: Cleanup and Teardown
253
254Clean up test resources after testing:
255
2561. Run cleanup script:
257 ```bash
258 bash scripts/cleanup-test-resources.sh
259 ```
260
261 This removes:
262 - Test users and sessions
263 - Test data from tables
264 - Temporary test databases
265 - Test file uploads
266
2672. Reset test database:
268 ```bash
269 # Reset to clean state
270 supabase db reset --linked
271
272 # Or use migration-based reset
273 bash scripts/reset-test-db.sh
274 ```
275
276## Test Coverage Areas
277
278### Database Testing
279- **Schema Validation**: Table structure, columns, constraints
280- **Migration Testing**: Up/down migrations, rollback safety
281- **RLS Policies**: Access control, policy enforcement
282- **Functions & Triggers**: Database logic, event handlers
283- **Performance**: Query optimization, index usage
284
285### Authentication Testing
286- **User Flows**: Signup, login, logout, password reset
287- **Provider Integration**: OAuth, magic links, phone auth
288- **Session Management**: Token refresh, expiration, persistence
289- **MFA**: Setup, verification, recovery codes
290- **Security**: Rate limiting, brute force protection
291
292### AI Features Testing
293- **Vector Operations**: Insert, update, delete embeddings
294- **Similarity Search**: Accuracy, relevance, threshold tuning
295- **Index Performance**: HNSW vs IVFFlat, query speed
296- **Hybrid Search**: Combined keyword and semantic search
297- **Dimension Validation**: Embedding size consistency
298
299### Realtime Testing
300- **Subscriptions**: Database changes, broadcasts, presence
301- **Connection Management**: Connect, disconnect, reconnect
302- **Message Delivery**: Ordering, reliability, deduplication
303- **Performance**: Latency, throughput, concurrent users
304- **Cleanup**: Subscription disposal, memory leaks
305
306### Integration Testing
307- **Multi-Component**: Auth + Database + Storage
308- **User Journeys**: Complete workflows end-to-end
309- **Error Scenarios**: Network failures, invalid data, rate limits
310- **Edge Cases**: Concurrent updates, race conditions, timeouts
311
312## Test Data Strategies
313
314### Fixture Management
315```typescript
316// Load test fixtures
317const testData = await loadFixtures('users', 'posts', 'comments');
318
319// Seed database
320await seedDatabase(testData);
321
322// Cleanup after tests
323afterAll(async () => {
324 await cleanupFixtures();
325});
326```
327
328### Factory Patterns
329```typescript
330// Create test users with factories
331const user = await createTestUser({
332 email: 'test@example.com'
333 metadata: { role: 'admin' }
334});
335
336// Create related data
337const posts = await createTestPosts(user.id, 5);
338```
339
340### Isolation Strategies
341- **Test Database**: Dedicated test project
342- **Transaction Rollback**: Rollback after each test
343- **Namespace Prefixes**: `test_` prefix for test data
344- **Time-based Cleanup**: Delete data older than X hours
345
346## Performance Benchmarks
347
348### Query Performance Targets
349- Simple queries: < 50ms
350- Vector similarity search: < 100ms
351- Hybrid search: < 200ms
352- Complex joins: < 300ms
353
354### Realtime Latency Targets
355- Message delivery: < 100ms
356- Presence updates: < 200ms
357- Database changes: < 500ms
358
359### Throughput Targets
360- Authenticated requests: 100+ req/s
361- Vector searches: 50+ req/s
362- Realtime messages: 1000+ msg/s
363
364## Common Test Patterns
365
366### Pattern 1: Auth-Protected Resource Test
367```typescript
368test('authenticated user CRUD operations', async () => {
369 // 1. Sign up user
370 const { user } = await supabase.auth.signUp({
371 email: 'test@example.com'
372 password: 'test123'
373 });
374
375 // 2. Create resource
376 const { data } = await supabase
377 .from('notes')
378 .insert({ content: 'test note' })
379 .select()
380 .single();
381
382 // 3. Verify ownership
383 expect(data.user_id).toBe(user.id);
384
385 // 4. Update resource
386 await supabase
387 .from('notes')
388 .update({ content: 'updated' })
389 .eq('id', data.id);
390
391 // 5. Delete resource
392 await supabase.from('notes').delete().eq('id', data.id);
393});
394```
395
396### Pattern 2: Vector Search Workflow Test
397```typescript
398test('document RAG workflow', async () => {
399 // 1. Upload document
400 const doc = await uploadDocument('test.pdf');
401
402 // 2. Generate embeddings
403 const chunks = await chunkDocument(doc);
404 const embeddings = await generateEmbeddings(chunks);
405
406 // 3. Store in database
407 await supabase.from('document_chunks').insert(
408 chunks.map((chunk, i) => ({
409 content: chunk
410 embedding: embeddings[i]
411 document_id: doc.id
412 }))
413 );
414
415 // 4. Perform semantic search
416 const query = 'What is the main topic?';
417 const queryEmbedding = await generateEmbedding(query);
418
419 const { data } = await supabase.rpc('match_documents', {
420 query_embedding: queryEmbedding
421 match_count: 5
422 });
423
424 // 5. Verify results
425 expect(data.length).toBeGreaterThan(0);
426 expect(data[0].similarity).toBeGreaterThan(0.7);
427});
428```
429
430### Pattern 3: Realtime Collaboration Test
431```typescript
432test('multi-user realtime chat', async () => {
433 // 1. Create two users
434 const user1 = await createTestUser();
435 const user2 = await createTestUser();
436
437 // 2. Subscribe to messages
438 const user1Messages = [];
439 const user2Messages = [];
440
441 const sub1 = await subscribeToMessages(user1, user1Messages);
442 const sub2 = await subscribeToMessages(user2, user2Messages);
443
444 // 3. User 1 sends message
445 await sendMessage(user1, 'Hello from user 1');
446
447 // 4. Verify both users receive it
448 await waitFor(() => {
449 expect(user1Messages).toHaveLength(1);
450 expect(user2Messages).toHaveLength(1);
451 });
452
453 // 5. Cleanup subscriptions
454 await sub1.unsubscribe();
455 await sub2.unsubscribe();
456});
457```
458
459## Troubleshooting
460
461### Tests Failing Intermittently
462- **Race Conditions**: Add proper wait conditions
463- **Async Issues**: Ensure all promises are awaited
464- **Cleanup**: Verify test isolation and cleanup
465- **Timeouts**: Increase timeout for slow operations
466
467### Tests Passing Locally but Failing in CI
468- **Environment**: Verify env variables in CI
469- **Timing**: CI may be slower, increase timeouts
470- **Parallelization**: Check for shared state issues
471- **Dependencies**: Ensure all deps are installed
472
473### Slow Test Execution
474- **Parallel Tests**: Use `--maxWorkers` flag
475- **Test Selection**: Run only changed tests
476- **Database Reset**: Use faster cleanup methods
477- **Mocking**: Mock external services
478
479### Database Connection Issues
480- **Connection Pooling**: Limit concurrent connections
481- **Cleanup**: Properly close connections after tests
482- **Retries**: Implement connection retry logic
483- **Timeouts**: Set appropriate connection timeouts
484
485## Files Reference
486
487**Scripts:**
488- `scripts/setup-test-env.sh` - Initialize test environment
489- `scripts/run-e2e-tests.sh` - Execute complete test suite
490- `scripts/test-database-workflow.sh` - Database E2E tests
491- `scripts/test-auth-workflow.sh` - Authentication E2E tests
492- `scripts/test-ai-features.sh` - Vector search E2E tests
493- `scripts/test-realtime-workflow.sh` - Realtime E2E tests
494- `scripts/cleanup-test-resources.sh` - Clean up test data
495- `scripts/validate-schema.sh` - Validate database schema
496- `scripts/benchmark-vector-search.sh` - Performance benchmarks
497- `scripts/reset-test-db.sh` - Reset test database
498
499**Templates:**
500- `templates/test-suite-template.ts` - Jest/Vitest boilerplate
501- `templates/database-tests.ts` - Database operation tests
502- `templates/auth-tests.ts` - Authentication flow tests
503- `templates/vector-search-tests.ts` - pgvector tests
504- `templates/realtime-tests.ts` - Realtime subscription tests
505- `templates/ci-config.yml` - GitHub Actions CI/CD
506- `templates/jest.config.js` - Jest configuration
507- `templates/vitest.config.ts` - Vitest configuration
508
509**Examples:**
510- `examples/complete-test-workflow.md` - Full E2E testing guide
511- `examples/ci-cd-integration.md` - CI/CD setup guide
512- `examples/test-data-strategies.md` - Test data management
513- `examples/performance-benchmarks.md` - Performance testing
514- `examples/mocking-strategies.md` - Mocking external services
515
516---
517
518**Plugin**: supabase
519**Version**: 1.0.0
520**Last Updated**: 2025-10-26