When using Cypress for automated testing, setting and using environment variables is a crucial feature that helps manage configuration information across different environments (such as development, testing, and production). Cypress provides several methods for setting and retrieving environment variables, which I will detail below.
1. Setting Environment Variables via Configuration File
Cypress allows setting environment variables in the cypress.json configuration file. These variables are loaded when tests run. For example, if you want to set an environment variable to specify the API endpoint, you can do this in cypress.json:
json{ "env": { "apiUrl": "https://api.example.com" } }
In test files, you can use Cypress.env('apiUrl') to retrieve this environment variable:
javascriptdescribe('API Tests', () => { it('can reach the API', () => { cy.request(`${Cypress.env('apiUrl')}/health`).then((response) => { expect(response.status).to.eq(200); }); }); });
2. Setting Environment Variables via Command Line
You can also override settings in cypress.json by setting environment variables with the CYPRESS_ prefix in the command line. For example, if you want to set the apiUrl environment variable in the command line, you can do this:
bashCYPRESS_apiUrl=https://api.staging.example.com npx cypress run
In this case, regardless of the apiUrl setting in cypress.json, Cypress.env('apiUrl') will return 'https://api.staging.example.com'.
3. Dynamically Setting Environment Variables Using Plugins
For more complex environment variable management, such as dynamically setting variables based on different test scenarios, you can use Cypress plugins like cypress-dotenv. This plugin loads environment variables from a .env file, making them available in Cypress.
First, install cypress-dotenv:
bashnpm install cypress-dotenv
Then, in the cypress/plugins/index.js file, import and use this plugin:
javascriptconst dotenvPlugin = require('cypress-dotenv'); module.exports = (on, config) => { config = dotenvPlugin(config); return config; };
Now, you can set environment variables in a .env file, and cypress-dotenv will automatically load them into Cypress environment variables.
Conclusion
By using the methods above, you can flexibly manage and utilize environment variables across different test phases and environments, ensuring the accuracy and efficiency of tests. In practice, selecting the appropriate method for setting environment variables based on project-specific requirements is crucial.