运行 Cypress 测试时,如何指定用于我的开发服务器的 .env 文件?

gra*_*ury 5 environment-variables node.js cypress

运行 Cypress 测试时,如何指定.env开发服务器使用哪个文件?这些是系统级环境变量,而不是赛普拉斯测试环境变量。

我有一个 env 文件,我想在运行 cypress 测试时将其用于我的服务器:.env.local.cypress

在我的package.json文件中我有:

"dev-server": "nodemon --delay 5ms -e ts,tsx --watch ./src -x ts-node --transpile-only ./src/server",
"cy:run": "cypress run",
"test:e2e:local": "dotenv -e .env.local.cypress -- start-server-and-test dev-server http://localhost:3000 cy:run"
Run Code Online (Sandbox Code Playgroud)

当我运行时,test:e2e:local服务器以正确的环境变量启动,但测试却没有。有什么想法吗?

use*_*029 6

cypress.config.js您可以通过多种方式获取任何全局环境变量。

通过 dotenv CLI(根据您的示例)

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     
    },
  },
})
Run Code Online (Sandbox Code Playgroud)

这为您提供当前在系统级别定义的所有内容,包括通过 dotenv CLI 添加的内容。

您只需添加特定的变量即可:

config.env = {
  abc: process.env.abc,
  ...config.env                  
}
Run Code Online (Sandbox Code Playgroud)

通过本地 dotenv 安装

或者您可以在本地使用该dotenv包来仅加载其中的特定环境文件cypress.config.js

npm install dotenv --save
Run Code Online (Sandbox Code Playgroud)
const { defineConfig } = require("cypress");

const local = require('dotenv').config({ path: '.env.local.cypress' })

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      config.env = {
        ...local.parsed,
        ...config.env               
      }
      return config     
    },
  },
})
Run Code Online (Sandbox Code Playgroud)