为何.env.test变量无法触发Playwright启动Web Server?
问题:Playwright webServer逻辑无法读取.env.test中的ENVIRONMENT变量
问题描述
- 需求:当
ENVIRONMENT环境变量设为LOCAL时,让Playwright自动启动Web服务器 - 异常现象:通过
dotenv.config({ path: '.env.test' })加载的ENVIRONMENT变量无法触发webServer的启动逻辑;只有通过shell命令export ENVIRONMENT='LOCAL' yarn playwright test手动设置变量时,逻辑才生效 - 补充:
constants.ts中的E2E_BASE_URL能正常读取.env.test里的变量,说明dotenv已正确加载文件,问题仅出在测试进程启动阶段的webServer条件判断
配置代码示例
import { defineConfig, devices } from '@playwright/test'; import * as dotenv from 'dotenv'; import { defineBddConfig } from 'playwright-bdd'; import { E2E_BASE_URL, E2E_SERVER_PORT } from './constants'; dotenv.config({ path: '.env.test' }); const testDir = defineBddConfig({ features: '*.feature', steps: ['*.ts'], outputDir: '.temp/specs', quotes: 'single', }); export default defineConfig({ timeout: 30_000, testDir, outputDir: '.temp/results', snapshotPathTemplate: 'snapshots/{testName}/{platform}-{projectName}/{arg}.{ext}', reporter: [['html', { outputFolder: '.temp/report' }]], use: { baseURL: E2E_BASE_URL, screenshot: 'only-on-failure', video: 'retain-on-failure', ignoreHTTPSErrors: true, trace: 'on-first-retry', testIdAttribute: 'data-tracking-id', }, webServer: process.env.ENVIRONMENT === 'LOCAL' ? { command: `yarn codegen && next dev -p ${E2E_SERVER_PORT}`, url: E2E_BASE_URL, reuseExistingServer: !process.env.CI, } : undefined, fullyParallel: true, forbidOnly: Boolean(process.env.CI), retries: process.env.CI ? 2 : 0, workers: process.env.CI ? 1 : 5, projects: [ { name: 'Chrome', use: { ...devices['Desktop Chrome'] }, fullyParallel: true, testMatch: '*.feature.spec.js', }, ], });
问题原因
- dotenv默认不覆盖已有环境变量:dotenv的默认行为是仅加载系统中不存在的环境变量,如果shell环境中已经存在
ENVIRONMENT变量(哪怕是空值),dotenv会保留原有值,不会用.env.test中的值覆盖它 - 变量覆盖差异:
constants.ts能读取到变量,说明dotenv确实加载了文件,但webServer依赖的ENVIRONMENT恰好被系统环境变量覆盖,导致条件判断不成立
解决方案
方案1:强制dotenv覆盖已有环境变量
修改dotenv的加载配置,添加override: true选项,强制用.env.test中的值覆盖系统已有的环境变量:
dotenv.config({ path: '.env.test', override: true });
方案2:确保dotenv在所有模块导入前加载
将dotenv的加载逻辑移到文件最顶部,确保在Playwright、playwright-bdd等模块加载前完成环境变量设置:
// 先加载环境变量 import * as dotenv from 'dotenv'; dotenv.config({ path: '.env.test', override: true }); // 再导入其他模块 import { defineConfig, devices } from '@playwright/test'; import { defineBddConfig } from 'playwright-bdd'; import { E2E_BASE_URL, E2E_SERVER_PORT } from './constants';
方案3:检查.env.test文件的变量正确性
确认.env.test文件中的变量名和值符合要求,注意环境变量名区分大小写:
# .env.test文件内容 ENVIRONMENT=LOCAL E2E_BASE_URL=http://localhost:3000 E2E_SERVER_PORT=3000
验证方式
直接运行yarn playwright test,观察Playwright是否自动启动Web服务器,以此验证逻辑是否生效。
内容的提问来源于stack exchange,提问作者Leandro Zanchin
相关产品推荐
相关产品推荐

