4

How can I specify which .env file to use for my dev server when running cypress tests? These are system level env vars not cypress test env vars.

I have an env file that I want to use for my server when running cypress tests: .env.local.cypress

In my package.json file I have:

"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"

When I run test:e2e:local the server starts with the correct env vars but the tests do not. Any ideas why?

grabury
  • 4,797
  • 14
  • 67
  • 125

1 Answers1

4

You can pick up any global env variables in cypress.config.js in a couple of ways.

Via dotenv CLI (as per your example)

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     
    },
  },
})

That gives you everything currently defined at system level, including those added via dotenv CLI.

You can just add specific vars:

config.env = {
  abc: process.env.abc,
  ...config.env                  
}

Via local dotenv install

Or you can use the dotenv package locally to load just the specific env file inside cypress.config.js

npm install dotenv --save
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     
    },
  },
})
user16695029
  • 3,365
  • 5
  • 21