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:
bashcypress 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.