1

i've been trying to figure out how to specify which .env file to use when running Cypress Component tests for a while now but can't seem to figure it out or find any information about it online.

I've noticed when you mount a Component in Cypress and run some Component Tests, the component will pick up process.env variables from the .env file by default. However, I would instead like Cypress to pick up process.env variables from my .env.test file. Does anyone know how to specify which .env file your component should get process.env variables from when running component tests?

I am currently just running the following command from my package.json file "test-e2e": "cypress open". This opens the Cypress test runner where I can select Component Testing and then select a spec file to run tests against. The component in question uses some process.env variables which I can see are being taken from the .env file which seems to be the default. I can't find any flags I can add to my npm command to instead tell Cypress to take them from the .env.test file instead.

Any help would be much appreciated!

MickyDore
  • 146
  • 6

1 Answers1

3

You want to do something like this answer How can I get Vite env variables.

Note that the .env section of config is outside of component or e2e sections (common to both).

const { defineConfig } = require("cypress");
const dotenv = require('dotenv')
const env = dotenv.config('./.env.test').parsed

module.exports = defineConfig({
  'component': {
    // component config here
  },
  env: {
    login_url: '/login',
    ...env,                        // merge here with spread operator
  },
});
Woof
  • 201
  • 7