Reputation: 29
I am using Quasar, Vue 3, Vite, Cypress in my project. I don't know how to get .env
variables (e.g. VITE_API_URL
) and to set in cypress.env.json
. Before Vite I used webpack and I know how to do it.
I don't want to define twice same variable, first in .env
then in cypress.env.json
.
Upvotes: 2
Views: 2168
Reputation: 2869
You can use cypress-plugin-dotenv to share .env
files with Cypress app. This plugin is also introduced on official cypress plugins docs. It works for Vite with react or vue, create-react-app, Turborepo, and many other frameworks and setups.
Installation:
npm install cypress-plugin-dotenv
Usage:
import { dotenv } from 'cypress-plugin-dotenv';
// or
const dotenv = require('cypress-plugin-dotenv');
export default defineConfig({
e2e: {
setupNodeEvents: (_, config) => {
return dotenv(config);
}
}
});
Now go to your spec file and just use Cypress.env('YOUR_ENV')
Upvotes: 0
Reputation: 241
You can use the dotenv
package directly, merging the result in with the env
section of your cypress config.
.env
VITE_API_URL: "http://example.com"
cypress.config.js
const { defineConfig } = require("cypress");
const dotenv = require('dotenv')
const env = dotenv.config('./.env').parsed
module.exports = defineConfig({
'component': {
// component config here
},
env: {
login_url: '/login',
...env, // merge here with spread operator
},
});
Settings page in the Cypress runner
env: {
login_url: '/login',
VITE_API_URL: 'http://example.com',
},
Upvotes: 4
Reputation: 993
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.
npm install --save-dev cypress-dotenv
# For typescript
npm install --save-dev @types/cypress-dotenv
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'));
});
dotenvCypress()
must be returned in setupNodeEvents()
.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
Upvotes: 0