Setup environment variables in cypress: A comprehensive guide.

8 months ago - 2 MIN READ - jidanmaharjan1

Education
Setup environment variables in cypress: A comprehensive guide.

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

  1. Install cypress.

    npm i cypress

    or

    yarn add cypress
  2. Create a .env file

    touch .env
  3. Add environment variables

    AUTH_EMAIL="example@gmail.com"
    AUTH_PASSWORD="passwordexample"
  4. Install dotenv package

    npm i dotenv

    or

    yarn add dotenv
  5. In cypress.config.js, import the package and initialize it.

    require('dotenv').config()
  6. 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.

  7. To use it in cypress test, follow this syntax:

    Cypress.env('email')
    Cypress.env('password')
  8. 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

  1. Create a cypress.env.json

    touch cypress.env.json
  2. Add variables

    {
      "base_url": "example.test.com",
      "email": "test@example.com"
    }
AD SECTION
AD SECTION

Trending

Fix High CPU usage (winlogui.exe)

9 months ago - 3 MIN READ

Manual Testing: Things you must know immediately

9 months ago - 5 MIN READ

How to setup weak password in Ubuntu

8 months ago - 2 MIN READ

Fix files being tracked even after adding to gitignore

8 months ago - 2 MIN READ

Setup GIT using SHH: An Ultimate Guide

6 months ago - 2 MIN READ

Cypress: Generate reports of automated tests

6 months ago - 2 MIN READ

Use cypress tags (grepTags): An Ultimate guide.

6 months ago - 2 MIN READ

Subscribe to Newsletter !