如何通过GitHub Action向Cypress传递环境变量?
问题背景
本地Cypress配置的baseUrl为https://localhost:3000,需要在GitHub Action运行测试时替换为开发环境URL,同时传递DEV_TOKEN作为请求头以确保请求能正常访问开发环境。但多次尝试后,Action始终使用localhost的baseUrl,导致Cypress无法连接服务器报错。
尝试过的无效方案
- 使用
process.env.CYPRESS_XYZ和Cypress.env('XYZ')读取环境变量来覆盖baseUrl - 在GitHub Action的yaml文件
with:部分设置config: baseUrl=https://xyz
报错信息
Cypress could not verify that this server is running:
https://localhost:3000
We are verifying this server because it has been configured as your baseUrl.
Cypress automatically waits until your server is accessible before running tests.
We will try connecting to it 3 more times...
We will try connecting to it 2 more times...
We will try connecting to it 1 more time...Cypress failed to verify that your server is running.
最终解决步骤
1. 修改cypress.config.ts
将原本通过环境变量动态设置的baseUrl改为固定值:
// 修改前 e2e: { baseUrl: process.env.CYPRESS_BASE_URL || 'https://localhost:3000', experimentalRunAllSpecs: true, // ...其他配置 } // 修改后 e2e: { baseUrl: 'https://localhost:3000', experimentalRunAllSpecs: true, // ...其他配置 }
2. 修改GitHub Action配置文件(e2e.yaml)
在Cypress Action的with:字段中添加config参数,直接指定baseUrl:
# 修改前 - name: Cypress run uses: cypress-io/github-action@v5 with: browser: chrome record: true parallel: true env: DEV_TOKEN: ${{ secrets.DEV_TOKEN }} CYPRESS_BASE_URL: ${{ inputs.E2E_BASE_URL }} CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # 修改后 - name: Cypress run uses: cypress-io/github-action@v5 with: browser: chrome record: true parallel: true config: baseUrl=${{ inputs.E2E_BASE_URL }} # 新增这一行 env: DEV_TOKEN: ${{ secrets.DEV_TOKEN }} CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
原因推测
之前的失败大概率是输入失误导致,比如yaml文件中config参数的位置写错,或者环境变量名未正确对应,导致Cypress没有读取到期望的配置值。
内容的提问来源于stack exchange,提问作者KungWaz

