diff --git a/tests/fixtures/database.ts b/tests/fixtures/database.ts index cbb176f3..5ffd7daa 100644 --- a/tests/fixtures/database.ts +++ b/tests/fixtures/database.ts @@ -34,19 +34,32 @@ export async function setupTestUser( throw new Error('Service role key not configured'); } - // Create user in auth - const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({ - email, - password, - email_confirm: true, - }); + // Check if user already exists + const { data: existingUsers } = await supabaseAdmin.auth.admin.listUsers(); + const existingUser = existingUsers?.users.find(u => u.email === email); - if (authError) throw authError; - if (!authData.user) throw new Error('User creation failed'); + let userId: string; - const userId = authData.user.id; + if (existingUser) { + // User exists - use their ID + userId = existingUser.id; + console.log(`ℹ️ Using existing test user: ${email}`); + } else { + // User doesn't exist - create new one + const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({ + email, + password, + email_confirm: true, + }); - // Create profile + if (authError) throw authError; + if (!authData.user) throw new Error('User creation failed'); + + userId = authData.user.id; + console.log(`✓ Created new test user: ${email}`); + } + + // Create or update profile (ensures correct role and is_test_data flag) const { error: profileError } = await supabaseAdmin .from('profiles') .upsert({