0
0
CypressHow-ToBeginner ยท 4 min read

How to Use Environment Variables in Cypress for Testing

In Cypress, you can use environment variables to store configuration or secrets by defining them in cypress.config.js, cypress.env.json, or via CLI with --env. Access these variables in tests using Cypress.env('variableName') to keep your tests flexible and secure.
๐Ÿ“

Syntax

Environment variables in Cypress can be set in multiple ways:

  • cypress.config.js: Define under env property.
  • cypress.env.json: Store variables in a JSON file.
  • CLI: Pass variables using --env key=value.

Access variables in tests with Cypress.env('key').

javascript
module.exports = {
  env: {
    apiUrl: 'https://api.example.com',
    userToken: 'abc123'
  }
};

// In test file
const apiUrl = Cypress.env('apiUrl');
const token = Cypress.env('userToken');
๐Ÿ’ป

Example

This example shows setting environment variables in cypress.config.js and accessing them in a test to visit a URL and use a token.

javascript
// cypress.config.js
module.exports = {
  env: {
    baseUrl: 'https://example.com',
    authToken: 'securetoken123'
  }
};

// cypress/e2e/sample_spec.cy.js
describe('Environment Variable Test', () => {
  it('uses env variables to visit and authenticate', () => {
    const url = Cypress.env('baseUrl');
    const token = Cypress.env('authToken');

    cy.visit(url);
    cy.log('Token:', token);
    // Example assertion
    expect(token).to.be.a('string').and.to.have.length.greaterThan(0);
  });
});
Output
Test passes if token is a non-empty string and page visits successfully.
โš ๏ธ

Common Pitfalls

Common mistakes when using Cypress environment variables include:

  • Not restarting Cypress after changing cypress.config.js or cypress.env.json.
  • Trying to access variables with wrong key names or case sensitivity.
  • Exposing sensitive data in public repos by committing cypress.env.json.
  • Using process.env instead of Cypress.env() inside tests.
javascript
// Wrong way (won't work inside Cypress test)
const token = process.env.authToken;

// Right way
const token = Cypress.env('authToken');
๐Ÿ“Š

Quick Reference

MethodHow to SetAccess in TestNotes
cypress.config.jsAdd under env propertyCypress.env('key')Requires Cypress restart after change
cypress.env.jsonCreate JSON file with key-value pairsCypress.env('key')Do not commit secrets to public repos
CLIRun: cypress run --env key=valueCypress.env('key')Overrides config and JSON variables
System EnvironmentSet OS env vars before running CypressCypress.env('key')Use for CI/CD secrets
โœ…

Key Takeaways

Set environment variables in cypress.config.js, cypress.env.json, or via CLI with --env.
Access variables in tests using Cypress.env('variableName') for flexibility.
Never commit sensitive data in cypress.env.json to public repositories.
Restart Cypress after changing config files to load new variables.
Use CLI or system environment variables to override config for different environments.