Skip to content

Cypress - 环境变量

Cypress 中的环境变量允许你存储和管理可在整个测试套件中访问的配置值。这对于定义基础 URL、API 密钥、用户凭据或任何可能在不同环境(例如,开发、预发布、生产)或测试运行之间变化的数据非常有用。

在 Cypress 中定义环境变量有几种方法:

1. 配置文件 (cypress.config.js 或 cypress.config.ts)

Section titled “1. 配置文件 (cypress.config.js 或 cypress.config.ts)”

你可以在 Cypress 配置文件的 env 对象中定义环境变量。这是项目特定变量最常用且推荐的方式。

在 cypress.config.js 中的示例:

const { defineConfig } = require('cypress');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
},
baseUrl: 'http://localhost:3000',
env: {
apiUrl: 'https://api.example.com/v1',
username: 'testUser',
// Add other environment variables here
},
},
});

你可以在运行 Cypress 时使用 --env 标志(或 -e)直接通过命令行传递环境变量。这对于覆盖配置文件中的值或用于 CI/CD 管道非常有用。

npx cypress run --env username=admin,password=secret123

或者对于单个变量:

npx cypress open -e apiUrl=https://staging-api.example.com

通过 CLI 传递的值将覆盖配置文件中设置的值。

Cypress 会自动识别以 CYPRESS_ 为前缀的操作系统环境变量。例如,如果你设置了一个操作系统环境变量 CYPRESS_API_KEY=yourkey123,它将在你的测试中通过 Cypress.env('API_KEY') 可用。

# In your terminal (Linux/macOS)
export CYPRESS_API_KEY=yourkey123
npx cypress run
# In your terminal (Windows PowerShell)
$env:CYPRESS_API_KEY = "yourkey123"
npx cypress run

这种方法对于敏感数据(如 API 密钥)特别有用,因为你不想将它们提交到你的仓库中。

你可以在测试文件中使用 Cypress.env() 命令访问环境变量:

describe('Environment Variable Test', () => {
it('should use environment variables', () => {
const apiUrl = Cypress.env('apiUrl');
const username = Cypress.env('username');
cy.visit(Cypress.config('baseUrl')); // 从配置中访问 baseUrl
cy.log(`API URL: ${apiUrl}`);
cy.log(`Username: ${username}`);
// 示例用法:
// cy.request(`${apiUrl}/users?username=${username}`).then((response) => {
// expect(response.status).to.eq(200);
// });
});
});

Cypress 根据以下优先级顺序(从高到低)确定环境变量的值:

  1. CLI 参数 (--env)。
  2. 以 CYPRESS_ 为前缀的操作系统环境变量。
  3. 在 cypress.config.js 或 cypress.config.ts 文件中 env 对象内定义的变量。
  • **基础 URL:**为不同环境定义不同的 baseUrl 或 API 端点。
  • **凭据:**存储测试用户凭据(但对于登录流程,请考虑使用 cy.session())。
  • **功能标志:**根据功能标志控制测试执行。
  • **API 密钥:**安全地提供 API 密钥,尤其是在 CI 中使用操作系统环境变量时。

有效使用环境变量可以使你的 Cypress 测试在不同测试阶段和设置中更加灵活、可配置和易于维护。