Cypress Cucumber测试在GitHub Actions中执行失败求助
核心问题分析
本地执行npx cypress run可正常跑通所有测试,但GitHub Actions中出现AssertionError: Timed out retrying after 4000ms,这类问题大多由环境差异或配置遗漏导致,结合你提供的配置,重点排查以下几点:
1. 未启动被测应用服务
你的GitHub Actions工作流中注释了start: npm start,但本地测试时应该是先启动了应用服务(比如本地先跑npm start再执行测试)。GitHub Actions是全新的隔离环境,没有运行应用服务,测试无法访问页面元素,必然触发超时。
解决方法:
取消注释start: npm start,确保Cypress在启动测试前先拉起应用服务:
with: start: npm start command: npx cypress run
如果应用启动需要较长时间,可添加wait-on依赖让Cypress等待服务就绪后再执行测试:
- 安装依赖:
npm install wait-on --save-dev - 修改工作流命令:
command: npx wait-on http://localhost:3000 && npx cypress run
(将http://localhost:3000替换为你的应用实际地址)
2. 依赖版本冲突
你的package.json中同时安装了两个功能重叠的Cucumber预处理器:
@badeball/cypress-cucumber-preprocessor(v17.0.0,新版官方维护)cypress-cucumber-preprocessor(v4.3.1,旧版已弃用)
两个包同时存在会导致预处理器逻辑混乱,引发测试执行异常。
解决方法:
删除旧版依赖,保留新版:
npm uninstall cypress-cucumber-preprocessor
同时确保Cypress配置文件(cypress.config.js)中正确配置新版预处理器,示例:
const createEsbuildPlugin = require('@badeball/cypress-cucumber-preprocessor/esbuild').createEsbuildPlugin; const createBundler = require('@bahmutov/cypress-esbuild-preprocessor'); const nodePolyfills = require('@esbuild-plugins/node-modules-polyfill').NodeModulesPolyfillPlugin; module.exports = defineConfig({ e2e: { specPattern: 'cypress/e2e/**/*.feature', setupNodeEvents(on, config) { const bundler = createBundler({ plugins: [nodePolyfills(), createEsbuildPlugin(config)], }); on('file:preprocessor', bundler); }, }, });
3. 浏览器环境差异
GitHub Actions默认使用Electron浏览器,和本地常用的Chrome/Firefox可能存在渲染差异,导致元素加载速度变慢或定位失败。
解决方法:
指定使用Chrome浏览器执行测试,修改工作流中的command:
command: npx cypress run --browser chrome
注:cypress-io/github-action已预装Chrome,无需额外配置。
4. 调整超时时间
GitHub Actions的虚拟机资源有限,元素加载速度可能比本地慢,默认4000ms超时时间可能不足。
解决方法:
在Cypress配置文件中全局调整超时时间:
module.exports = defineConfig({ e2e: { defaultCommandTimeout: 10000, // 调整为10秒 pageLoadTimeout: 60000, // 页面加载超时调整为60秒 }, });
或者在单个断言中单独设置超时:
cy.get('.target-element', { timeout: 10000 }).should('be.visible');
5. 增加调试信息
开启DEBUG日志后,可查看更详细的测试执行过程,定位具体是哪个元素或步骤超时。同时可配置Cypress在失败时自动截图、录屏,方便排查:
修改工作流配置,启用截图和录屏:
uses: cypress-io/github-action@v4.2.0 env: DEBUG: "cypress:*" with: start: npm start command: npx cypress run --browser chrome upload-screenshots: true # 自动上传失败截图
内容的提问来源于stack exchange,提问作者Joee

