Open In App

Environment Variables in Cypress

Last Updated : 21 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Cypress is a modern front-end test instrument. One can write strong, reliable end-to-end tests using Cypress which should ensure that applications are running smoothly and securely. A vital aspect of the flexibility and maintainability of Cypress tests lies in its utilization of environment variables. Cypress environment variables are used to store dynamically changing configuration data through the key-value pair structure.

These variables allow testing to be carried out differently depending on the environments it is done either development, staging, or production hence streamlining the process greatly. Instead of having such values as API endpoints, authentication credentials or feature flags hard-coded into your test scripts, they can be defined as environment variables. This makes your tests easily readable and manageable besides boosting security by not including private information in your code base.

What are the Environmental Variables in Cypress?

Cypress environment variables are dynamic key-value pairs that configure different aspects of your test setup. They offer an adaptable, secure way to handle various settings across multiple environments i.e. development, staging and production. The values themselves can be set directly into the scripts that run the tests but this approach is not recommended as it makes our code less maintainable and more difficult to reuse or configure in other environments.

For example, one might want to have different base URLs for their application in development and production environment. Through the use of environment variables, you can easily change between these two URLs without having to modify your test code.

Definitely, by using environment variables you will be able to design flexible, secure and adaptable cypress tests that take into account different operating states which will improve overall efficiency and reliability of your test suites.

How to Access Environment Variables in Cypress?

Multiple ways of accessing environment variables in Cypress make it flexible enough to be able to configure tests dynamically. The following are the ways you can use to access these variables:

  • Using cypress.env.json File: Cypress.env.json is a simple way of setting up environment variables. It should be placed in root directory of your project.
  • Using the Command Line with --env Option: Command line with an environmental option –env allows direct manipulation of environment variables via command line, which is usually temporary or when using CI/CD pipelines.
  • Using Shell Environment Variables: Setting environment variables through your shell before running Cypress is another method that might be more suitable for temporary settings.
  • Using cypress.config.js Plugins: You can also set environment variables within the Cypress plugins file (cypress.config.js) especially if you have complex configurations or dynamic setups.
  • Directly in Test Scripts: Though not common, some test scripts allow direct definition of environment variables for smaller and specific tests.

This way, your testing process becomes flexible and maintainable by seamlessly adapting them into different environments securely feeling confident about it.

How to set Environment variables in Cypress?

Environment variables can be set in Cypress in a variety of ways, each suitable for different situations and needs. Below are some brief descriptions of these methods:

  • Using the cypress.env.json File: Cypress.env.json is a simple and effective way to define static environment variables. Copy this file into the root folder of your Cypress project. These variables are accessible in your tests by using Cypress.env ().
  • Using the Command-Line --env Option: The --env flag enables you to set environment variables via the command line directly. This method is especially helpful in CI/CD pipelines and temporary configurations. This means that you can either overrule other environmental variables provisioned or put new ones on demand.
  • Using Shell Environment Variables: Setting environment variables in your shell is an alternative approach, best suited for transient settings during a session. As long as your shell session remains active, these environmental factors will be reachable from within your Cypress tests.
  • Using cypress.config.js Plugins: In cypress.config.js i.e., Cypress plugins file one may set environment variables for more complex dynamic setups. This option allows adjusting defaults based on external factors like conditions existing outside it or other scripts.

By ensuring that you select the right process, you’ll make sure that you have flexible Cypress tests.

How to Set Environment Variables Using the 'cypress.env.json' File?

Definition of Cypress.env.json file is an effortless and efficient approach to creating environment variables for use in your tests in Cypress. You can set key value pairs in it that are accessible across your test suite thereby making it easier to manage configurations for different environments.

Step 1. How to create the cypress.env.json File: Locate the cypress.env.json file within the root directory of the Cypress project. Make a new file known as cypress.env.json if it does not exist.

Step 2. Defining Environment Variables: In JSON format, add key-value pairs to cypress.env.json file where each key represents an environment variable name and its corresponding value is what you want set.

Example cypress.env.json

{

"API_URL": "https://api.example.com",

"USERNAME": "testuser",

"PASSWORD": "securepassword"

}

Step 3. Accessing Environment Variables in Tests: Use Cypress.env() method in your test files to use those which were declared in the cypress.env.json file.

Example

JavaScript
describe('Environment Variables Test', () => {
  it('should access environment variables', () => {
    const apiUrl = Cypress.env('API_URL');
    const username = Cypress.env('USERNAME');
    const password = Cypress.env('PASSWORD');

    cy.visit(apiUrl);
    cy.get('#username').type(username);
    cy.get('#password').type(password);
    cy.get('#login-button').click();
  });
});

Benefits

  • Centralized Configuration: It ensures all environment-specific settings are kept together.
  • Ease of Use: A simple JSON format enables easy reading and editing.
  • Security: It helps keep sensitive information off from your test scripts.

The use of a cypress.env.json file is one of the best methods of handling environmental variables; thus, when using them, tests will be adaptable as well as maintainable on various environments.

How to Set Environment Variables Using 'export' on the Command-Line?

To make it simple to alter the environment variables, you can use the export command on a command-line. This is done in two cases: when one only needs temporary configurations or when tests need to be run in different environments. Below is a step-by-step guide on how to do this:

Step 1. Open Your Command-Line Interface: Begin by opening your terminal or command line interface where Cypress tests will be run.

Step 2. Set Environment Variables Using export: The export command should be used for setting environment variables. The format is export VARIABLE_NAME=value, and these values are set for the active shell session.

export CYPRESS_API_URL=https://api.example.com

export CYPRESS_USERNAME=testuser

export CYPRESS_PASSWORD=securepassword

In this case, CYPRESS_API_URL, CYPRESS_USERNAME and CYPRESS_PASSWORD are set during the session with the test runner. It is important to note that although using CYPRESS_ as a prefix is common, it is not obligatory.

Step 3. Run Cypress: At this point, you may choose either cypress open for interactive or cypress run for headless mode after setting up your environment variables.

Cypress open

Step 4. Access Environment Variables in Your Tests: You can use Cypress.env() method in your Cypress test files to access these environment variables.

Example

JavaScript
describe('Environment Variables Test', () => {
  it('should access environment variables set in the shell', () => {
    const apiUrl = Cypress.env('API_URL');
    const username = Cypress.env('USERNAME');
    const password = Cypress.env('PASSWORD');

    cy.visit(apiUrl);
    cy.get('#username').type(username);
    cy.get('#password').type(password);
    cy.get('#login-button').click();
  });
});


Step 5. Verify Environment Variables: Use echo command in terminal to confirm that you have set right environment variables.

Example

echo $CYPRESS_API_URL

echo $CYPRESS_USERNAME

echo $CYPRESS_PASSWORD

Using export on the command-line to set environment variables provides a quick and efficient way of dynamically configuring your Cypress tests.

How to Set Environment Variables Using the '--env' Option on the Command-Line?

Configuring the Cypress tests dynamically through setting environment variables using --env option on command line is an easier way. It is most especially convenient in a continuous integration (CI) setup or when you want to run the same test with different settings but without having to change your configuration files.

Step 1. Open Your Command-Line Interface: Begin by opening your terminal/command-line interface of choice where you will be running Cypress tests.

Step 2. Use the –env Option: While running Cypress; use the –env option followed by key-value pairs separated by commas. Each key represents a name of an environment variable and its corresponding value should be used as the value for that key.

cypress run --env API_URL=https://api.example.com,USERNAME=testuser,PASSWORD=securepassword

Or for opening the Cypress Test Runner:

cypress open --env API_URL=https://api.example.com,USERNAME=testuser,PASSWORD=securepassword

Step 3. Access Environment Variables in Your Tests: Within your Cypress test files, you can access these environmental variables via Cypress.env () method.

Example

JavaScript
describe('Environment Variables Test', () => {
  it('should access environment variables set via --env option', () => {
    const apiUrl = Cypress.env('API_URL');
    const username = Cypress.env('USERNAME');
    const password = Cypress.env('PASSWORD');

    cy.visit(apiUrl);
    cy.get('#username').type(username);
    cy.get('#password').type(password);
    cy.get('#login-button').click();
  });
});


Step 4. Combining with Other Options: In addition, you can combine this option with other Cypress CLI options such as specifying the browser or choosing a spec file you want to execute.

Example:

cypress run --env API_URL=https://api.example.com,USERNAME=testuser,PASSWORD=securepassword --spec "cypress/integration/tests/my_test_spec.js" --browser chrome

Benefits

  • Flexibility: Change and set up environment variables quickly minus modifying either codebase or configuration files.
  • Temporary Settings: The values put for environment variables through –env are only applicable during that singular test run thereby guaranteeing non-persisted temporary configurations.

How to Set Environment Variables Using Plugins in Cypress

Setting environment variables using plugins in Cypress allows for advanced and dynamic configurations. This method is beneficial when you want to customize surroundings variables primarily based on external situations or other runtime criteria. Cypress plugins are configured in the cypress.config.js file, which is located at the root of your project.

Step 1. Open the cypress.config.js File: Find and open the cypress.config.js file in your project’s root directory. If it doesn’t exist, create it.

Step 2. Configure Environment Variables in the Plugin: Use the module.exports to define a function that sets environment variables. This function receives two arguments: on (to hook into various Cypress events) and config (the resolved Cypress configuration).

JavaScript
module.exports = (on, config) => {
  // Set environment variables dynamically
  config.env.API_URL = process.env.API_URL || 'https://default-api.example.com';
  config.env.USERNAME = process.env.USERNAME || 'defaultuser';
  config.env.PASSWORD = process.env.PASSWORD || 'defaultpassword';

  // Return the updated configuration
  return config;
};

In this example, the environment variables API_URL, USERNAME, and PASSWORD are set using values from the system environment variables (process.env). If these are not defined, default values are used.

Step 3. Run Cypress: Start Cypress using your preferred method (cypress open or cypress run). The environment variables configured in the cypress.config.js file will be available during the test execution.

cypress open

Step 4. Access Environment Variables in Your Tests: Use the Cypress.env() method in your test files to access the environment variables set in the plugin configuration.

Example

JavaScript
describe('Environment Variables Test', () => {
  it('should access environment variables set in the plugin', () => {
    const apiUrl = Cypress.env('API_URL');
    const username = Cypress.env('USERNAME');
    const password = Cypress.env('PASSWORD');

    cy.visit(apiUrl);
    cy.get('#username').type(username);
    cy.get('#password').type(password);
    cy.get('#login-button').click();
  });
});

Benefits

  • Dynamic Configuration: lets you to set Environment variables based totally on external conditions or runtime parameters.
  • Centralized Management: Keeps all configuration logic in one place, making it easier to manage and update.
  • Flexibility: gives a manner to apply system environment variables and set defaults, making sure your tests run easily in exclusive environments.

The use of plugins to set environment variables in Cypress is a powerful technique for coping with complicated and dynamic configurations. This technique ensures that your check environment is customized exactly to your needs, improving the reliability and versatility of your check suite.

Conclusion

Environment variables in Cypress play a crucial role in enhancing the flexibility, maintainability, and security of your test automation suite. By leveraging environment variables, you can create tests that adapt seamlessly to various environments without hardcoding sensitive or environment-specific data directly into your test scripts.

Incorporating surroundings variables into your Cypress checking out method no longer only streamlines the checking out manner but also enhances collaboration amongst individuals by presenting a consistent and configurable trying out surroundings. whether you are a solo developer or part of a large QA team, learning the usage of surroundings variables in Cypress will notably improve the performance and reliability of your automated assessments.


Next Article

Similar Reads