0

I want to find out if cypress runs or doesn't run in the NextJS application. My idea is prevent a some http requests in the NextJS application if the Cypress tests are running.

I am able to catch if cypress is running when I run "npx cypress open" for a browser like this:

if(window.Cypress){
 // prevent http request or do something
}

But I am not able to check if the cypress is running or not in headless mode with "npx cypress run" command.

I tried to add extra env variable in the package.json file like in below:

...
"cy:run": "cross-env CY_MODE=true cypress run",
...

But it doesn't set the CY_MODE env variable when I try to log process.env.CY_MODE.

How can I set a custom environment variable before cypress tests start with headless mode?

Thanks

Fody
  • 23,754
  • 3
  • 20
  • 37
tcetin
  • 979
  • 1
  • 21
  • 48

2 Answers2

1

From Exposing Environment Variables to the Browser

By default environment variables are only available in the Node.js environment, meaning they won't be exposed to the browser.

In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_.

"cy:run": "cross-env NEXT_PUBLIC_CY_MODE=true cypress run",

Alternatively, you can control the NextJs server from Cypress plugins - see Mock Network When Using Next.js getServerSideProps Call

Fody
  • 23,754
  • 3
  • 20
  • 37
0

You can set env.variables inside package.json:

  • create parent command where you define env.variable and contain your command for running tests 'parentCommand': 'cross-env CY_MODE=true npx cypress run'
  • launch the command and env variable will be shared between files and applications
  • I tried --env CY_MODE=true this one but in headless mode for cypress I don't know if it is set. So I need to check if it was set when I run "npx cypress run". But I cannot see anything in console.log https://docs.cypress.io/guides/guides/environment-variables#Option-4-env It is setting cypress env variable but I need to set node env variable to check in NextJS – tcetin May 16 '22 at 13:34
  • you can check your env variables in the test runner -> open test runner -> click on settings link = and you can check all variables that related cypress – Denys Pavliuk May 16 '22 at 13:38
  • Yes I can see. But I am not able to use this env variable in a javascript code for the NextJS. I can access this by Cypress.env('CY_MODE') in a cypress spec file but I need to access this env variable into the NextJS not in Cypress. Hope it is clear for you. – tcetin May 16 '22 at 13:41