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