Setting an environment variable in Javascript project is relatively simpler than in cypress. Some packages have rules for how environment needs to be setup. Just like that cypress also has a unique way to use and setup environment variables. Let's get started by setup cypress.
Method 1
Install cypress.
npm i cypress
or
yarn add cypress
Create a .env file
touch .env
Add environment variables
AUTH_EMAIL="example@gmail.com" AUTH_PASSWORD="passwordexample"
Install dotenv package
npm i dotenv
or
yarn add dotenv
In cypress.config.js, import the package and initialize it.
require('dotenv').config()
We cannot use environment variables in cypress directly. We need to setup it in the config file. Config will look like this:
module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { // implement node event listeners here }, env: { email: process.env.AUTH_EMAIL, password: process.env.AUTH_PASSWORD, }, }, });
Here is how it works, Cypress will understand that there is an environment variable email and password which has the value process.env.AUTH_EMAIL and process.env.AUTH_PASSWORD which is from the environment variable we setup.
To use it in cypress test, follow this syntax:
Cypress.env('email') Cypress.env('password')
To hide the variables in the log:
cy.get('input[type=email]').type(Cypress.env('email'), { log: false }) cy.get('input[type=password]').type(Cypress.env('password'), { log: false })
Method 2
Create a cypress.env.json
touch cypress.env.json
Add variables
{ "base_url": "example.test.com", "email": "test@example.com" }