Cypress - Environment Variables


We can define environment variables that can be globally declared for the test automation framework and all the test cases can access it. This type of customized environment variable can be stored in the cypress.json file within our project.

Cypress JSON

Since, a customized variable is not exposed by default configurations from Cypress, we have to mention the key as "evn" in the cypress.json file and then, set the value.

Also, to access this variable in the actual test, we have to use the Cypress.env and pass the value declared in the json file.

Implementation in cypress.json

The implementation of commands for environment variables in cypress.json format is as follows −

{
   "projectId": "fvbpxy",
   "env" :
   {
      "url" : "https://www.google.com/"
   }
}

Implementation of Actual Test

The implementation of actual test for environmental variables in Cypress is as follows −

describe('Tutorialspoint Test', function () {
   // test case
   it('Scenario 1', function (){
      // launch application from environment variable
      cy.visit(Cypress.env('url'))
      cy.getCookies()
      cy.setCookie('cookie1', 'value1')
   });
});

Execution Results

The output is as follows −

Output Logs

The output logs show the URL launched which has been set as a customized environment variable from the cypress.json file.

Configure Environment Variables

We can configure or modify the environment values from the command line with the flag --env.

To run a particular file (for example: Test1.js) with URL: https://accounts.google.com in a headed mode, the command shall be as follows:

./node_modules/.bin/cypress run --spec cypress/integration/examples/Test1.js --
env url=https://accounts.google.com –headed

If we have a value set for the environment variable url in the cypress.json file, which is different from the value set from the command line, Cypress shall give preference to the value set from the command line.

Advertisements