Environment variables let you change settings without changing your test code. This helps tests run in different places easily.
Environment variables for configuration in 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.
Cypress.env('baseUrl')baseUrl.cy.visit(Cypress.env('baseUrl'))username and password in the config file.// cypress.config.js module.exports = { e2e: { env: { username: 'testuser', password: 'mypassword' } } }
baseUrl when running tests.// Run test with env variable from command line npx cypress run --env baseUrl=https://example.com
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.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') }) })
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.
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.