Set env variables in Cypress using Vite

Viewed 109

I'm using VueJs 3 with Vite and Cypress.

In my app I have an environment variable to define my URL:

const url = import.meta.env.VITE_URL

My goal is to replace this VITE_URL in Cypress. I've tried to create a cypress.env.json file in which I wrote:

{
      "VITE_URL": "https://...",
}

but it's not working. I've also tried with CYPRESS_URL or CYPRESS_VITE_URL, but I get the same result. Any idea?

3 Answers

If you've declared the value in a cypress.env.json file, you can reference it in code with `Cypress.env('varName');

Cypress.env('VITE_URL');

If you want to change the url the app sees when Cypress is running, you might be able to do it like this.

// vue3 app code

const envVar = window.Cypress ? 'CYPRESS_VITE_URL' : 'VITE_URL'
const url = import.meta.env[envVar];

Ok, I solved it. I created a .env.testing file that I use by specifying --mode testing in the npm command that launches cypress.

This env.testing has the properties defined like:

'VITE_URL="http://..."'
Related