There is a plugin called cypress-dotenv
for this very purpose. It allows you to share your .env
file variables between your app and cypress tests.
Install
npm install --save-dev cypress-dotenv
# For typescript
npm install --save-dev @types/cypress-dotenv
Example
Example .env
file
VITE_API_URL=https://vite-api-url.com
In your cypress.config.js
, run the plugin dotenvCypress()
under setupNodeEvents()
:
import { defineConfig } from "cypress";
import dotenvCypress from 'cypress-dotenv';
export default defineConfig({
component: {
devServer: {
framework: "vue",
bundler: "vite",
},
setupNodeEvents(on, config) {
return dotenvCypress(config, undefined, true);
},
},
});
Then in your test:
it('works', () => {
cy.log(Cypress.env('VITE_API_URL'));
});
Notes
dotenvCypress()
must be returned in setupNodeEvents()
- To get all the env variables from your
.env
file, you have to pass true
as the third argument to dotenvCypress()
. Otherwise, only vars prefixed with CYPRESS_
will be available.
https://www.npmjs.com/package/cypress-dotenv