We are using cypress to run automated tests and need to pass an environment variable to detect whether the app is run by cypress or not?
I’m aware that NODE_ENV
is set automatically by react to development | production but is there any way to add ‘integration’ to it when running by cypress?
I tried passing a custom env variable REACT_APP_ENV
while running the command REACT_APP_ENV=integration npx cypress open --e2e --browser=chrome
and accessing it in App.tsx file with process.env.REACT_APP_ENV
but got below error:
(uncaught exception)ReferenceError: process is not defined
Did some search on stackoverflow and the answers mentioned to remove explicit cypress imports from test files but my files aren’t importing any.
The only import is done in cypress.config.json
file to define the config(defineConfig).
It would be really helpful if someone could assist me with this.
Thank you in advance.
2
Answers
The reason for the error of
process
not being found is how environment variables in a React application are embedded at build time, not runtime.The process object is a Node.js feature and doesn’t exist in browser environments.
So your command
REACT_APP_ENV=integration npx cypress open --e2e --browser=chrome
is set for the Cypress process but not React app.You have to build your application with
npm run build
An alternative to checking an environment variable is to check for the
Cypress
property on thewindow
object.The Cypress runner adds this before opening the app.
For example from the cypress-example-recipes
App.jsx
Another example from a React component test in the main Cypress repo: cypress/npm/react/cypress/component/advanced/app-action-example
/counter.jsx