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

global-setup.ts

153 lines4.2 KB

1import { Client } from 'pg'
2import type { ClientConfig } from 'pg'
3import type { TestProject } from 'vitest/node'
4​
5const ELECTRIC_URL = process.env.ELECTRIC_URL ?? 'http://localhost:3000'
6const POSTGRES_HOST = process.env.POSTGRES_HOST ?? 'localhost'
7const POSTGRES_PORT = parseInt(process.env.POSTGRES_PORT ?? '54321')
8const POSTGRES_USER = process.env.POSTGRES_USER ?? 'postgres'
9const POSTGRES_PASSWORD = process.env.POSTGRES_PASSWORD ?? 'password'
10const POSTGRES_DB = process.env.POSTGRES_DB ?? 'e2e_test'
11const TEST_SCHEMA = 'e2e_test'
12​
13// Module augmentation for type-safe context injection
14declare module 'vitest' {
15 export interface ProvidedContext {
16 baseUrl: string
17 testSchema: string
18 postgresConfig: {
19 host: string
20 port: number
21 user: string
22 password: string
23 database: string
24 }
25 }
27​
28/**
29 * Create a PostgreSQL client with default e2e test configuration
30 */
31export function makePgClient(overrides: ClientConfig = {}): Client {
32 return new Client({
33 host: POSTGRES_HOST,
34 port: POSTGRES_PORT,
35 user: POSTGRES_USER,
36 password: POSTGRES_PASSWORD,
37 database: POSTGRES_DB,
38 options: `-csearch_path=${TEST_SCHEMA}`,
39 ...overrides,
40 })
42​
43/**
44 * Wait for Electric server to be ready
45 */
46async function waitForElectric(url: string): Promise<void> {
47 return new Promise<void>((resolve, reject) => {
48 const timeout = setTimeout(() => {
49 reject(new Error(`Timed out waiting for Electric to be active at ${url}`))
50 }, 10000)
51​
52 const check = async (): Promise<void> => {
53 try {
54 const res = await fetch(`${url}/v1/health`)
55 if (res.ok) {
56 const data = (await res.json()) as { status: string }
57 if (data.status === 'active') {
58 clearTimeout(timeout)
59 return resolve()
60 }
61 }
62 setTimeout(() => void check(), 100)
63 } catch {
64 setTimeout(() => void check(), 100)
65 }
66 }
67​
68 void check()
69 })
71​
72/**
73 * Wait for Postgres to be ready
74 */
75async function waitForPostgres(client: Client): Promise<void> {
76 return new Promise<void>((resolve, reject) => {
77 const timeout = setTimeout(() => {
78 reject(new Error('Timed out waiting for Postgres'))
79 }, 10000)
80​
81 const check = async (): Promise<void> => {
82 try {
83 await client.connect()
84 clearTimeout(timeout)
85 return resolve()
86 } catch {
87 setTimeout(() => void check(), 100)
88 }
89 }
90​
91 void check()
92 })
94​
95/**
96 * Global setup for e2e test suite
97 *
98 * This runs once before all tests and:
99 * 1. Waits for Electric server to be healthy
100 * 2. Connects to Postgres
101 * 3. Creates test schema
102 * 4. Provides context to all tests
103 * 5. Returns cleanup function
104 */
105export default async function ({ provide }: TestProject) {
106 console.log('🚀 Starting e2e test suite global setup...')
107​
108 // Wait for Electric server to be ready
109 console.log(`⏳ Waiting for Electric at ${ELECTRIC_URL}...`)
110 await waitForElectric(ELECTRIC_URL)
111 console.log('✓ Electric is ready')
112​
113 // Connect to Postgres
114 console.log(
115 `⏳ Connecting to Postgres at ${POSTGRES_HOST}:${POSTGRES_PORT}...`,
116 )
117 const client = makePgClient()
118 await waitForPostgres(client)
119 console.log('✓ Postgres is ready')
120​
121 // Create test schema
122 console.log(`⏳ Creating test schema: ${TEST_SCHEMA}...`)
123 await client.query(`CREATE SCHEMA IF NOT EXISTS ${TEST_SCHEMA}`)
124 console.log('✓ Test schema created')
125​
126 // Provide context values to all tests
127 provide('baseUrl', ELECTRIC_URL)
128 provide('testSchema', TEST_SCHEMA)
129 provide('postgresConfig', {
130 host: POSTGRES_HOST,
131 port: POSTGRES_PORT,
132 user: POSTGRES_USER,
133 password: POSTGRES_PASSWORD,
134 database: POSTGRES_DB,
135 })
136​
137 console.log('✅ Global setup complete\n')
138​
139 // Return cleanup function (runs once after all tests)
140 return async () => {
141 console.log('\n🧹 Running global teardown...')
142 try {
143 await client.query(`DROP SCHEMA IF EXISTS ${TEST_SCHEMA} CASCADE`)
144 console.log('✓ Test schema dropped')
145 } catch (error) {
146 console.error('Error dropping test schema:', error)
147 } finally {
148 await client.end()
149 console.log('✓ Postgres connection closed')
150 console.log('✅ Global teardown complete')
151 }
152 }