我正在开发几年前从 create-react-app 引导的 React 应用程序。
该应用程序有一个包含许多变量的
.env.dev
文件。
启动脚本是"start": "env-cmd -f .env.dev --use-shell \"react-scripts start\"",
React 脚本版本:
"react-scripts": "^4.0.1",
当我
console.log("gggg", process.env);
时,我得到了所有变量。
当我:
describe('Login via API', () => {
it('Test login', () => {
console.log('teeest', process.env)
cy.login()
})
})
相反,我得到了一个空物体。
我尝试阅读问题如何在 Cypress 运行的浏览器中使用 process.env 变量
但是这个问题并没有回答我关于如何使 process.env 变量可用于 Cypress 测试文件的问题。
这个问题还说要安装
dotenv
。 Dotenv 附带了react-scripts,因此如果应用程序是通过create-react-app 创建的,则无需安装它。
我也尝试过这个: 在
cypress.config.js
我添加了:
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
config.env = process.env
return config
}
}
})
在规范中,我尝试获取
.env.dev
文件中定义的变量:
it('Test login', () => {
console.log('new', Cypress.env('REACT_APP_USERNAME'))
cy.login()
})
仍然
undefined
。
任何人都可以帮我理解出了什么问题吗?我怎样才能让它发挥作用?
编辑: 根据这里的答案我尝试安装 dotenv:
npm install dotenv --save
测试中导入:
导入“dotenv/config”
describe('通过API登录', () => { it('测试登录', () => { console.log('newwwww', Cypress.env('REACT_APP_USERNAME')) console.log('teeest', process.env) cy.login() }) })
Npm start
npm run cypress:open
结果:
newwwww undefined
login-test.cy.js:7 teeest {}
谢谢
当您使用
"start": "env-cmd -f .env.dev --use-shell \"react-scripts start\""
时,env-cmd
命令特定于 React 应用程序的进程。
在 cypress 打开其进程之前,您需要运行相同的内容
{
...
"dependencies": {
...
},
"scripts": {
"cy:open": "env-cmd -f .env.dev cypress open",
...
}
}
我还建议使用 spread 运算符,如下所示,否则您将丢失以其他方式添加的任何环境变量,例如命令行添加。
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
config.env = {
...process.env, // add all process env var here
...config.env // plus any command line overrides
}
return config // return the altered config
},
},
env: {
login_url: '/login', // define some specific env var here
products_url: '/products'
}
});
如果您查看 Cypress 运行程序中的
Settings/Project Settings
,您会看到大量来自通用机器环境变量的不必要的设置。
仅选择带有前缀
REACT_
, 的那些
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
const reactEnv = Object.keys(process.env).reduce((obj, key) => {
if (key.startsWith('REACT_')) {
obj[key] = process.env[key];
}
return obj;
}, {});
config.env = {
...reactEnv, // add REACT_ process env var here
...config.env // plus any command line overrides
}
return config // return the altered config
},
},
env: {
login_url: '/login', // define some specific env var here
products_url: '/products'
}
});
关于 dotenv 包含在反应脚本中是正确的,但是要在测试文件中访问它,您必须显式导入它。
npm install dotenv
然后在你的赛普拉斯代码的顶部
import 'dotenv/config'
请参阅此处的使用说明 https://www.npmjs.com/package/dotenv