playwright/playwright.config.js
2025-03-25 17:13:39 +08:00

89 lines
2.5 KiB
JavaScript

// @ts-check
const {defineConfig, devices} = require('@playwright/test');
const testLifecycle = require('./src/hooks/testLifecycle');
const dotenv = require('dotenv');
// 根据环境加载对应的.env文件
const env = process.env.NODE_ENV || 'dev';
const envPath = `.env.${env}`;
dotenv.config({ path: envPath });
console.log(`[Playwright Config] 已加载环境配置: ${envPath}`);
/**
* Read environment variables and process them
*/
function getBaseUrl() {
const baseUrl = process.env.BASE_URL;
if (!baseUrl) {
throw new Error('BASE_URL environment variable is not set');
}
// 确保基础URL不包含hash和query参数
return baseUrl.split('#')[0].split('?')[0];
}
/**
* @see https://playwright.dev/docs/test-configuration
* @type {import('@playwright/test').PlaywrightTestConfig}
*/
const config = {
testDir: './tests',
/* 测试超时时间 */
timeout: parseInt(process.env.EXPECT_TIMEOUT || '30000'),
/* 每个测试的预期状态 */
expect: {
timeout: parseInt(process.env.EXPECT_TIMEOUT || '30000')
},
/* 测试运行并发数 */
fullyParallel: false,
forbidOnly: !!process.env.CI,
/* 失败重试次数 */
retries: process.env.CI ? 2 : 0,
workers: 1,
/* 测试报告相关 */
reporter: 'html',
/* 共享设置 */
use: {
/* 基础URL */
baseURL: getBaseUrl(),
/* 收集测试追踪信息 */
trace: 'on-first-retry',
/* 自动截图 */
screenshot: {
mode: 'only-on-failure'
},
/* 录制视频 */
video: 'retain-on-failure',
/* 浏览器配置 */
headless: process.env.BROWSER_HEADLESS === 'true',
viewport: {
width: parseInt(process.env.VIEWPORT_WIDTH || '1920'),
height: parseInt(process.env.VIEWPORT_HEIGHT || '1080')
},
/* 浏览器启动选项 */
launchOptions: {
slowMo: parseInt(process.env.BROWSER_SLOW_MO || '50'),
timeout: parseInt(process.env.BROWSER_TIMEOUT || '30000')
}
},
/* 配置不同的浏览器项目 */
projects: [
{
name: 'chromium',
use: {...devices['Desktop Chrome']},
},
],
/* 本地开发服务器配置 */
// webServer: {
// command: 'npm run start',
// port: 3000,
// reuseExistingServer: !process.env.CI,
// },
/* 全局设置和清理 */
globalSetup: './src/hooks/setup.js',
globalTeardown: './src/hooks/teardown.js'
};
module.exports = defineConfig(config);