You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化package.json中的E2E测试脚本以消除重复?

问题原因

你拆分后的脚本失效的核心问题,出在test:setup里的concurrently参数配置:
--kill-others --success first会在其中一个子命令执行成功后,立刻杀掉所有其他进程。当wait-on完成两个端口的检查后,这个子命令就宣告执行成功,concurrently会直接终止npm run dev进程,后续执行test:cafe时服务器已经停了,自然跑不起来。

解决方案

推荐两种既能减少冗余、又能保留原有运行逻辑的方案:

方案一:用环境变量动态传递测试参数(最稳妥)

把公共的启动+等待+测试逻辑抽成基础命令,通过环境变量指定不同的浏览器模式,既避免重复代码,又保留原有的concurrently生命周期管理:

"scripts": {
  "test:cafe": "testcafe ${TESTCAFE_BROWSER:-chrome}",
  "test:e2e-base": "concurrently --kill-others --success first 'npm run dev' 'wait-on http://localhost:8080/admin && wait-on http://localhost:8081/health && npm run test:cafe'",
  "test:e2e": "TESTCAFE_BROWSER=chrome npm run test:e2e-base",
  "test:e2e-headless": "TESTCAFE_BROWSER=chrome:headless npm run test:e2e-base"
}

执行时,test:e2e会将浏览器参数设为普通Chrome,test:e2e-headless设为无头模式,两者共用同一个test:e2e-base逻辑,测试完成后concurrently才会自动终止dev服务。

方案二:调整setup逻辑,让dev持续运行到测试结束

如果坚持拆分setup和测试命令,可以修改test:setup不自动终止dev,测试完成后手动杀掉进程(注意跨平台兼容性):

"scripts": {
  "test:setup": "npm run dev & wait-on http://localhost:8080/admin && wait-on http://localhost:8081/health",
  "test:cafe": "testcafe",
  "test:cafe-headless": "testcafe chrome:headless",
  "test:e2e": "npm run test:setup && npm run test:cafe && pkill -f 'npm run dev'",
  "test:e2e-headless": "npm run test:setup && npm run test:cafe-headless && pkill -f 'npm run dev'"
}

⚠️ 注意:pkill是Linux/macOS命令,Windows需要换成taskkill /F /IM node.exe /FI "WINDOWTITLE eq npm run dev",这种方式存在误杀其他进程的风险,不如方案一可靠。

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 10:15:47