Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 383
jepek Avatar asked Sep 06 '19 08:09

jepek


People also ask

How do you call an environment variable in Cypress?

Using your Cypress config fileAny key/value you set in your Cypress configuration file ( cypress. json by default) under the env key will become an environment variable that you can access using Cypress. env in your tests.

How do I set an environment variable in a process?

For setting environment variables, just use the Get Set method. Pass variables Name and Value as parameters and if use to define access level then must pass with it. For accessing the value then use the Set method to pass the access level parameter too.


1 Answers

You can use the configuration API and do something like this on your plugins file. Set config.env = process.env which will set your entire node env for Cypress.

// cypress/plugins/index.js
module.exports = (on, config) => {

  // modify env value
  config.env = process.env

  // return config
  return config
}

You can also selectively assign the values that you want with config.env.YOUR_VAR = process.env.YOUR_VAR.

like image 184
Diogo Rocha Avatar answered Oct 11 '22 12:10

Diogo Rocha