'How to use process.env variables in browser running by Cypress

In the source code of my application (React based on create-react-app) I'm using env variables like so: process.env.REACT_APP_API_URL which are stored in my .env.* files.

But when I run the same application under the Cypress the process.env object is empty. How can I provide these variables to be used in React application when it's running under Cypress?

I know that I have a possibility to set Cypress env variables but it is not what I want - this is a different scope.



Solution 1:[1]

Create cypress.env.json file that contains your environment variables:

{
  "api_url": "http://localhost:8080"
}

Then set process.env in your cypress/support/index.js:

...

before(() => {
  process.env. REACT_APP_API_URL = Cypress.env("api_url");
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Khoi