Configure Cypress Tests to Run on Multiple Environments Using Environment Variable and Custom Utility Class

Profile picture for user arilio666

In this article, we will be running cypress tests on multiple environments using a utility class.

1.) Utility File Creation.

  • Go to your cypress/support folder and create a file called utility.js.
  • From the project root, it should be inside the support folder.
  • Name it utility.js.

2.) Utility Class.

  • When the environmental variable is passed from the command line, we need to return the URL from the class file.
  • Inside the utility.js, add the following code.
export class Utility {
   getBaseUrl() {
       let envi = Cypress.env('ENV'); 
       if (envi == 'production') 
           return "https://www.proudction-website.com"; 
       else if (envi == 'staging')
           return "https://staging-website.com";
       else if (envi == 'qa')
           return "http://qa-website.com";
   }
}
  • envi gets the value of the environmental variable 'ENV.'
  • The simple if else is passed based on envi.
  • The function getBaseUrl() is created here, which will return a single URL based on the ENV we pass in the cmd line.

3.) Import Utility Class And Pass URL.

  • Our introductory utility class is now ready; we need to run this from the spec file.
  • Create a spec file and import the utility class.
import { Utility } from "../../support/utility";
Then write a simple visit test.
import { Utility } from "../../support/utility";
const url = new Utility().getBaseUrl();
describe('Verify Environment Config' + url, () => {
   it('Verify Environment', () => {
       cy.visit(url); //use url variable
   })
})
  • Object for the Utility class is created and then passed within the visit.

4.) Run

  • Now that all is done, let us run the utility class by providing the environment it needs to be run.
npx cypress run --spec cypress\e2e\Tests\ut.cy.js --env ENV='production'
  • This will run programsbuzz.com.
  • Likewise, we can change the ENV to the names we provided in the utility.

Conclusion:

  • This is how we can run the cypress test on the different environments using a simple utility class.