乐闻世界logo
搜索文章和话题

How to refer to environment variables in Cypress config files?

1个答案

1

There are two primary ways to reference environment variables in Cypress: direct reference via configuration files and setting them via the command line. Below are detailed steps and examples:

1. Referencing Environment Variables via Configuration File

Cypress enables direct reference to environment variables in its configuration file cypress.json. This can be achieved by using the env key.

Example cypress.json:

json
{ "env": { "login_url": "${LOGIN_URL}", "api_key": "${API_KEY}" } }

In the above example, ${LOGIN_URL} and ${API_KEY} are environment variables defined in the system. Cypress resolves their values during test execution.

2. Setting Environment Variables via Command Line

You can also pass environment variables using the --env flag in the command line, which is particularly useful for temporary setups or CI/CD environments.

Command Line Example:

bash
cypress run --env HOST_URL=http://example.com,API_KEY=12345

This method passes the environment variables to Cypress during test execution without hardcoding them in the configuration file.

Benefits of Using Environment Variables

The primary advantages include maintaining the security of sensitive information and providing configuration flexibility. For instance, you can switch between different API keys and endpoints for development and production environments without modifying the code. Simply set the appropriate variables in different environments.

Best Practices

  • Confidentiality: Ensure sensitive environment variables are not exposed in version control systems.
  • Documentation: Provide clear documentation for the environment variables used so team members understand their purposes.
  • Default Values: Define default values for environment variables in the code to ensure application functionality when variables are not properly set.
2024年6月29日 12:07 回复

你的答案