Cypress test
I am writing a cypress test for my Ionic React app, compiled using vite. Specifically, I want to intercept a request to my endpoint:
const baseUrl = someBaseUrl;
cy.intercept(`${baseUrl}/home`);
Now, because the baseUrl is specific to my environment, I declare it in my .env
file and specify it in .env.local
in root:
VITE_BASE_URL = https://example.com
Now the problem is, that it is not that trivial to load variables form .env
.
What I tried
- The naive approach is to just loaf id the same way I would load it elsewhere in the app:
const baseUrl = import.meta.env. VITE_BASE_URL // undefined
- Then next I turned to the Cypredd docs. Cypress offers
Cypress.env()
but this does not load the variables from.env
but fromcypress.config.ts
. This means I would have to duplicate all variables in.env
to thecypress.config.ts
to have them available in my tests. This solution is presented here for example. - I also tried using cypress-dotenv with this configuration:
Sadly, this configuration does not work because the module cannot be found. This might be because// cypress/plugins/index.js const dotenvPlugin = require('cypress-dotenv'); module.exports = (on, config) => { config = dotenvPlugin(config) return config }
cypress-dotenv
has never been updated in two years while cypress received five major updates. - And I tried to this code snipped which I got from this question:
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 }, }, })
While this solution will work for many, it does not in my specific case. This is because I use Vita to compile and also because my config is written in typescript so the syntax is a bit different too.
Question
Is there any easy way, to directly use variables from .env in Cypress?
And how can this not be a very standard problem with a very standard solution?
Solution
Eventually, I found that I don't even have to go the detour via the setupNodeEvents()
function. Vite has its own loadEnv
function, wich makes it very easy to set up the variables in the cypress config:
// cypress.config.ts
import { defineConfig } from 'cypress';
import { loadEnv } from 'vite';
export default defineConfig({
// ... other configs
env: {a
...loadEnv("development", process.cwd()) // inserts all environment variables
}
});
And then in my cypress code, they are available like this:
const baseUrl = Cypress.env('MY_BYSE_URL');