0
0
Cypresstesting~5 mins

Environment variables for configuration in Cypress

Choose your learning style9 modes available
Introduction

Environment variables let you change settings without changing your test code. This helps tests run in different places easily.

You want to run the same test on different websites like staging and production.
You need to hide sensitive data like passwords or API keys from your test code.
You want to change test settings like timeouts without editing tests.
You run tests on different machines or CI servers with different setups.
You want to keep your test code clean and reusable.
Syntax
Cypress
Cypress.env('VARIABLE_NAME')

// or set in cypress.config.js
// env: { VARIABLE_NAME: 'value' }

Use Cypress.env('VARIABLE_NAME') to get the value of an environment variable in your test.

You can set environment variables in cypress.config.js or via command line when running tests.

Examples
Get the base URL from environment variables to use in tests.
Cypress
Cypress.env('baseUrl')
Visit the website URL stored in the environment variable baseUrl.
Cypress
cy.visit(Cypress.env('baseUrl'))
Set environment variables username and password in the config file.
Cypress
// cypress.config.js
module.exports = {
  e2e: {
    env: {
      username: 'testuser',
      password: 'mypassword'
    }
  }
}
Override or set environment variable baseUrl when running tests.
Cypress
// Run test with env variable from command line
npx cypress run --env baseUrl=https://example.com
Sample Program

This test uses environment variables for the website URL, username, and password. It visits the URL, fills in the login form, and checks if login was successful by verifying the URL.

Cypress
// cypress.config.js
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    env: {
      baseUrl: 'https://staging.example.com',
      username: 'user123',
      password: 'pass123'
    },
    setupNodeEvents(on, config) {
      // implement node event listeners here if needed
    }
  }
})

// cypress/e2e/login.cy.js
describe('Login Test', () => {
  it('logs in using environment variables', () => {
    cy.visit(Cypress.env('baseUrl'))
    cy.get('#username').type(Cypress.env('username'))
    cy.get('#password').type(Cypress.env('password'))
    cy.get('button[type=submit]').click()
    cy.url().should('include', '/dashboard')
  })
})
OutputSuccess
Important Notes

Environment variables help keep sensitive data out of your test code.

You can override environment variables from the command line for flexibility.

Always use Cypress.env() to access variables inside tests for consistency.

Summary

Environment variables let you configure tests without changing code.

Set variables in cypress.config.js or via command line.

Use Cypress.env('VAR_NAME') to get values in tests.