When using Cypress for end-to-end testing, correctly setting and managing environment variables is crucial. Environment variables enable us to use different configurations across various environments (such as development, testing, and production) without modifying the code. Below are several methods to set environment variables in Cypress:
1. Through cypress.json Configuration File
Cypress allows direct setting of environment variables in its configuration file cypress.json. This is a straightforward approach, particularly suitable for variables that rarely change. For example:
json{ "baseUrl": "http://localhost:3000", "env": { "login_email": "user@example.com", "login_password": "password123" } }
In test code, we can access these variables using Cypress.env('login_email') and Cypress.env('login_password').
2. Through Command Line
We can pass environment variables via the command line when launching Cypress tests. This is ideal for temporarily modifying variables or using specific variables in isolated test runs. For example:
bashcypress run --env host=localHost,api_key=123456
After this setup, we can retrieve the corresponding values in tests using Cypress.env('host') and Cypress.env('api_key').
3. Using .env File
For scenarios requiring dynamic management of environment variables, we can leverage the dotenv package to load variables from a .env file. First, install dotenv:
bashnpm install dotenv
Then, in the Cypress plugin file cypress/plugins/index.js, load and configure dotenv:
javascriptrequire('dotenv').config() module.exports = (on, config) => { config.env.login_email = process.env.LOGIN_EMAIL; config.env.login_password = process.env.LOGIN_PASSWORD; return config; };
Next, set these variables in the .env file:
shellLOGIN_EMAIL=user@example.com LOGIN_PASSWORD=password123
4. Using Cypress's Environment Variable API
Cypress provides an API for dynamically setting environment variables. We can use these APIs in the plugin file to modify environment variables as needed:
javascriptmodule.exports = (on, config) => { config.env.login_email = 'anotheruser@example.com'; return config; };
Summary
Through these methods, Cypress offers flexible and powerful ways to manage environment variables to accommodate diverse testing requirements and environments. In practice, we can select the most appropriate method for setting environment variables based on the specific needs of the project and team.