简体   繁体   English

在 cypress 以无头模式运行之前,在 package.json 中添加 env 变量

[英]Add env variable in package.json brefore cypress runs in headless mode

I want to find out if cypress runs or doesn't run in the NextJS application.我想知道 cypress 是否在 NextJS 应用程序中运行。 My idea is prevent a some http requests in the NextJS application if the Cypress tests are running.如果赛普拉斯测试正在运行,我的想法是阻止 NextJS 应用程序中的一些 http 请求。

I am able to catch if cypress is running when I run "npx cypress open" for a browser like this:当我为这样的浏览器运行“npx cypress open”时,我能够捕捉到 cypress 是否正在运行:

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.但我无法使用"npx cypress run"命令检查 cypress 是否正在运行。

I tried to add extra env variable in the package.json file like in below:我尝试在package.json文件中添加额外的 env 变量,如下所示:

...
"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 .但是当我尝试记录process.env.CY_MODE时,它没有设置 CY_MODE 环境变量。

How can I set a custom environment variable before cypress tests start with headless mode?如何在 cypress 测试以无头模式开始之前设置自定义环境变量?

Thanks谢谢

You can set env.variables inside package.json:您可以在 package.json 中设置 env.variables:

  • create parent command where you define env.variable and contain your command for running tests 'parentCommand': 'cross-env CY_MODE=true npx cypress run'创建父命令,在其中定义 env.variable 并包含用于运行测试的命令'parentCommand': 'cross-env CY_MODE=true npx cypress run'
  • launch the command and env variable will be shared between files and applications启动命令和环境变量将在文件和应用程序之间共享

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.默认情况下,环境变量仅在 Node.js 环境中可用,这意味着它们不会暴露给浏览器。

In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_ .为了向浏览器公开变量,您必须在变量前面加上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或者,您可以从赛普拉斯插件控制 NextJs 服务器 - 请参阅使用 Next.js getServerSideProps 调用时的模拟网络

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM