import { chromium, FullConfig } from '@playwright/test'; import * as dotenv from 'dotenv'; import * as path from 'path'; // Load .env file from the wordpress-dev directory dotenv.config({ path: path.resolve(__dirname, '../../.env') }); const authFile = '.auth/test-trainer.json'; const loginUrl = '/community-login/'; // Adjust if slug changes async function globalSetup(config: FullConfig) { const { baseURL } = config.projects[0].use; const browser = await chromium.launch(); const page = await browser.newPage(); const username = process.env.TEST_TRAINER_USER; const password = process.env.TEST_TRAINER_PASSWORD; if (!username || !password) { throw new Error('TEST_TRAINER_USER or TEST_TRAINER_PASSWORD environment variables are not set.'); } if (!baseURL) { throw new Error('baseURL is not configured in playwright.config.ts'); } console.log(`\nLogging in as ${username} at ${baseURL}${loginUrl} to save state...`); try { await page.goto(`${baseURL}${loginUrl}`); await page.locator('#user_login').fill(username); await page.locator('#user_pass').fill(password); await page.locator('#wp-submit').click(); // Wait for successful login - check for dashboard URL or a known dashboard element // Adjust the URL check if the redirect goes elsewhere first await page.waitForURL('**/hvac-dashboard/'); // Wait for dashboard redirect console.log('Login successful, waiting for dashboard load...'); await page.waitForLoadState('networkidle'); // Wait for network activity to settle // Verify a dashboard element exists to be sure await page.locator('h1.entry-title:has-text("Trainer Dashboard")').waitFor({ state: 'visible', timeout: 10000 }); console.log('Dashboard loaded.'); // Save storage state from the browser context await page.context().storageState({ path: authFile }); console.log(`Storage state saved to ${authFile}`); } catch (error) { console.error('Error during global setup login:', error); // Optionally save a screenshot or trace on error // await page.screenshot({ path: 'global-setup-error.png' }); throw error; // Re-throw to fail the setup } finally { await browser.close(); } } export default globalSetup;