skip to Main Content

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


  1. 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

    REACT_APP_ENV=integration npm run build
    npx cypress open --e2e --browser=chrome
    
    Login or Signup to reply.
  2. An alternative to checking an environment variable is to check for the Cypress property on the window object.

    The Cypress runner adds this before opening the app.

    For example from the cypress-example-recipes

    App.jsx

    if (window.Cypress) {
      window.model = model
    }
    

    Another example from a React component test in the main Cypress repo: cypress/npm/react/cypress/component/advanced/app-action-example
    /counter.jsx

    import React from 'react'
    
    export class Counter extends React.Component {
      constructor (props) {
        super(props)
        this.state = {
          count: 0,
        }
    
        if (window.Cypress) {
          // if this component is mounted from inside Cypress Test Runner
          // then expose the reference to this instance
          // to allow controlling it from tests
          console.log(
            'set window.counter to this component in window',
            window.location.pathname,
          )
    
          window.counter = this
        } else {
          console.log('running outside Cypress')
        }
      }
    
      click = () => {
        this.setState({
          count: this.state.count + 1,
        })
      }
    
      render () {
        return <p onClick={this.click}>count: {this.state.count}</p>
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search