Playwright单配置测试正常,移入projects配置后出现连接拒绝错误
看起来你遇到了一个特别棘手的问题——明明是完全一样的配置,只要一放到Playwright的projects结构里,就直接触发连接拒绝的错误,单配置模式下却跑得好好的。我来帮你拆解可能的原因,以及针对性的解决办法:
先搞清楚核心疑问:Web服务真的启动了吗?
先观察运行测试时的终端输出:
- 如果完全看不到Vite的启动日志(比如
VITE vx.x.x ready in x ms这类信息),说明Playwright根本没触发webServer的启动,大概率是配置层级或识别出了问题; - 如果能看到Vite的启动日志,但测试还是报错,那就是Playwright没等服务完全就绪就急着跑测试了。
针对性解决办法
1. 强制让Playwright等待服务完全就绪
在project的webServer配置里加上waitFor和timeout选项,明确告诉Playwright必须等Vite服务完全可用再执行测试:
export default defineConfig({ testDir: 'test', outputDir: 'test-results', fullyParallel: true, projects: [ { name: 'security-wrapper', testMatch: '**/SecurityPrechecks.test.js', use: { baseURL: 'http://localhost:5173', }, webServer: { command: 'npx vite --host 0.0.0.0 --mode test', port: 5173, reuseExistingServer: !process.env.CI, // 新增:等待服务返回200状态码,确认服务就绪 waitFor: 'http://localhost:5173', // 延长超时时间,给Vite足够的启动时间 timeout: 30000, }, } ], reporter: [ ['list'], ], });
单配置模式下Playwright的默认等待逻辑可能更宽松,但切换到project模式后,必须显式指定等待条件才能避免提前执行测试。
2. 排查CI环境变量的干扰
你配置了reuseExistingServer: !process.env.CI,但在project模式下,process.env.CI的值可能和单配置时不一样(比如某些终端环境意外触发了CI变量)。可以先强制关闭服务复用,试试让Playwright每次都启动新的Vite服务:
webServer: { command: 'npx vite --host 0.0.0.0 --mode test', port: 5173, reuseExistingServer: false, // 强制启动新服务,排除复用的干扰 waitFor: 'http://localhost:5173', },
3. 临时将webServer移到全局配置验证
如果上面的方法都没用,可以先把webServer配置从project里移到全局,确认测试能正常运行后再逐步调整:
export default defineConfig({ testDir: 'test', outputDir: 'test-results', fullyParallel: true, // 全局启动webServer webServer: { command: 'npx vite --host 0.0.0.0 --mode test', port: 5173, reuseExistingServer: !process.env.CI, waitFor: 'http://localhost:5173', }, projects: [ { name: 'security-wrapper', testMatch: '**/SecurityPrechecks.test.js', use: { baseURL: 'http://localhost:5173', }, } ], reporter: [ ['list'], ], });
如果这样测试能通过,就说明问题出在project内部的webServer配置识别上,可能是Playwright版本的小bug或配置优先级的细微差异。
4. 手动验证服务可用性
先手动启动Vite服务:
npx vite --host 0.0.0.0 --mode test
等看到ready in x ms的日志后,再运行测试命令:
playwright test --project=security-wrapper
如果这样测试能通过,就坐实了是Playwright在project模式下没有正确等待服务启动的问题,那waitFor配置应该能彻底解决。
为什么单配置和project模式有差异?
Playwright在单配置模式下,webServer的启动逻辑和测试执行是强绑定的,会默认等待服务就绪;但切换到多project模式后,由于配置优先级、启动时序的细微调整,默认的等待逻辑可能失效,必须显式指定等待条件才能正常工作。
希望这些方法能帮你解决问题!
内容来源于stack exchange




