0
0
Cypresstesting~15 mins

Test configuration per environment in Cypress - Deep Dive

Choose your learning style9 modes available
Overview - Test configuration per environment
What is it?
Test configuration per environment means setting up different settings for your tests depending on where they run, like development, staging, or production. This helps tests behave correctly in each place without changing the test code. For example, URLs, credentials, or feature flags can differ per environment. It makes testing flexible and reliable.
Why it matters
Without environment-specific test configuration, tests might fail or give false results because they use wrong data or settings. Imagine testing a website using production data accidentally or trying to log in with test credentials on a live site. Proper configuration prevents costly mistakes and saves time by reusing tests safely across environments.
Where it fits
Before learning this, you should understand basic Cypress test writing and how to run tests. After this, you can learn about advanced test data management, continuous integration setups, and test reporting that depend on environment configurations.
Mental Model
Core Idea
Test configuration per environment means tailoring test settings so the same tests run correctly and safely in different places like development, staging, or production.
Think of it like...
It's like packing different clothes for different trips: you pack warm clothes for a cold place and light clothes for a hot place, but you use the same suitcase. The suitcase is your test code, and the clothes are the environment settings.
╔════════════════════════════════════╗
║          Test Configuration        ║
╠══════════════╦════════════════════╣
║ Environment  ║ Settings           ║
╠══════════════╬════════════════════╣
║ Development  ║ URL=dev.example.com║
║              ║ User=testUser      ║
╠══════════════╬════════════════════╣
║ Staging      ║ URL=staging.example.com║
║              ║ User=stageUser     ║
╠══════════════╬════════════════════╣
║ Production   ║ URL=example.com    ║
║              ║ User=prodUser      ║
╚══════════════╩════════════════════╝
Build-Up - 7 Steps
1
FoundationUnderstanding environment basics
🤔
Concept: Introduce what environments are and why they differ.
In software, environments are separate places where code runs: development (where developers work), staging (a test copy of production), and production (live site). Each environment can have different URLs, data, or features. Tests need to know which environment they run in to behave correctly.
Result
Learners understand the need for different settings per environment.
Knowing environments exist explains why tests can't use one fixed setup for all cases.
2
FoundationCypress config file basics
🤔
Concept: Learn how Cypress uses configuration files to set test settings.
Cypress uses a cypress.config.js file to store settings like baseUrl, timeouts, and environment variables. This file controls how tests run. You can set default values here that apply to all tests unless overridden.
Result
Learners see where test settings live and how Cypress reads them.
Understanding the config file is key to customizing tests without changing test code.
3
IntermediateUsing environment variables in Cypress
🤔Before reading on: do you think environment variables in Cypress are set only in the config file or can they come from outside sources? Commit to your answer.
Concept: Introduce Cypress environment variables and how to set them dynamically.
Cypress supports environment variables that can be set in the config file, via CLI, or in separate files. These variables can hold URLs, credentials, or flags. For example, you can run tests with `cypress run --env env=staging` to tell tests which environment to use.
Result
Tests can read environment variables to adjust behavior dynamically.
Knowing multiple ways to set environment variables allows flexible test runs without code changes.
4
IntermediateCreating multiple config files per environment
🤔Before reading on: do you think Cypress supports multiple config files for different environments natively or requires manual setup? Commit to your answer.
Concept: Learn how to organize separate config files for each environment.
You can create different config files like cypress.config.dev.js, cypress.config.staging.js, and cypress.config.prod.js. Each file sets environment-specific values like baseUrl. Then, run Cypress with the desired config file using `cypress run --config-file cypress.config.staging.js`.
Result
Tests run with the correct settings for each environment by choosing the config file.
Separating config files keeps environment settings clean and reduces mistakes.
5
IntermediateAccessing config and env in test code
🤔
Concept: Show how test code reads environment variables and config values.
Inside tests, use `Cypress.env('key')` to get environment variables and `Cypress.config('baseUrl')` for config values. For example, `cy.visit(Cypress.config('baseUrl'))` visits the right URL depending on environment.
Result
Tests adapt their actions based on environment settings.
Knowing how to read config in tests enables writing flexible, reusable tests.
6
AdvancedCombining environment variables with CI pipelines
🤔Before reading on: do you think CI pipelines can pass environment info to Cypress tests automatically or must it be hardcoded? Commit to your answer.
Concept: Learn how CI tools pass environment info to Cypress for automated testing.
In CI pipelines like GitHub Actions or Jenkins, you can set environment variables or pass CLI flags to Cypress. For example, a pipeline job for staging sets `CYPRESS_env=staging` and runs `cypress run --env env=staging`. This automates running tests in the right environment without manual changes.
Result
Tests run automatically in correct environments during continuous integration.
Integrating environment config with CI ensures reliable, automated testing across all stages.
7
ExpertDynamic config merging and runtime overrides
🤔Before reading on: do you think Cypress merges multiple config sources at runtime or uses only one source? Commit to your answer.
Concept: Explore how Cypress merges config from files, CLI, and environment variables at runtime.
Cypress merges config from the main config file, environment variables, CLI flags, and plugins. This allows dynamic overrides. For example, you can have a base config and override only baseUrl or env variables at runtime. Plugins can also modify config before tests run, enabling complex setups.
Result
Tests can adapt to complex scenarios with layered config sources.
Understanding config merging prevents conflicts and enables powerful, flexible test setups.
Under the Hood
Cypress loads configuration in a specific order: first from the default config file, then from environment-specific config files if specified, then from CLI flags, and finally from environment variables. It merges these sources, with later sources overriding earlier ones. During test runtime, Cypress exposes these settings via global objects accessible in test code. This layered approach allows flexible, dynamic configuration without changing test code.
Why designed this way?
This design allows maximum flexibility and separation of concerns. Developers can keep base settings in one place and override only what changes per environment. It supports automation pipelines and local testing without duplication. Alternatives like hardcoding settings in tests were rejected because they cause maintenance headaches and risk errors.
╔════════════════════╗
║  Base Config File  ║
╚════════════════════╝
          ↓
╔════════════════════╗
║ Env-Specific Config║
╚════════════════════╝
          ↓
╔════════════════════╗
║  CLI Flags & Env   ║
╚════════════════════╝
          ↓
╔════════════════════╗
║   Merged Config    ║
╚════════════════════╝
          ↓
╔════════════════════╗
║  Test Runtime Use  ║
╚════════════════════╝
Myth Busters - 4 Common Misconceptions
Quick: Do you think setting environment variables in Cypress config file alone is enough for all environments? Commit to yes or no.
Common Belief:Setting environment variables once in the main config file is enough for all environments.
Tap to reveal reality
Reality:Environment variables in the main config file are static and do not change per environment unless overridden externally.
Why it matters:Tests may run with wrong settings if environment-specific overrides are not applied, causing false failures or unsafe test runs.
Quick: Do you think Cypress automatically detects the environment based on URL or folder structure? Commit to yes or no.
Common Belief:Cypress automatically knows which environment it is running in by inspecting the URL or project folders.
Tap to reveal reality
Reality:Cypress does not auto-detect environment; you must explicitly specify environment variables or config files.
Why it matters:Assuming auto-detection leads to tests running with wrong configs, causing confusion and errors.
Quick: Do you think you can safely store production credentials in Cypress config files? Commit to yes or no.
Common Belief:It's safe to store all credentials, including production, directly in Cypress config files checked into source control.
Tap to reveal reality
Reality:Storing sensitive credentials in config files is insecure; environment variables or secret managers should be used instead.
Why it matters:Exposing production credentials risks security breaches and data leaks.
Quick: Do you think CLI flags override environment variables set in OS? Commit to yes or no.
Common Belief:Environment variables set in the operating system always override CLI flags.
Tap to reveal reality
Reality:CLI flags have higher priority and override environment variables set in the OS.
Why it matters:Misunderstanding override order can cause unexpected test behavior and debugging difficulties.
Expert Zone
1
Cypress merges config sources in a precise order, and knowing this order helps avoid subtle bugs when multiple overrides exist.
2
Using plugins to modify config at runtime allows dynamic environment setups based on complex logic, like feature flags or test tags.
3
Separating sensitive data from config files and injecting them via CI environment variables is a best practice for security and compliance.
When NOT to use
Avoid per-environment config if your tests are simple and run only in one environment. Instead, hardcode minimal config. For complex multi-environment projects, use config files and environment variables. If you need full test isolation per environment, consider containerized test environments or separate test projects.
Production Patterns
In real projects, teams maintain separate config files per environment in version control, use CI pipelines to inject environment variables, and keep secrets in vaults or encrypted stores. Tests read config dynamically to run against multiple environments without code changes. Plugins often customize config for feature toggles or test parallelization.
Connections
Continuous Integration (CI)
Builds-on
Understanding test configuration per environment helps integrate tests smoothly into CI pipelines that run tests automatically in different stages.
Secrets Management
Complementary
Knowing how to separate sensitive data from config files connects to secrets management practices that protect credentials during testing.
Supply Chain Management
Analogous process
Just like supply chains adjust materials and processes per destination, test configuration adapts settings per environment to ensure smooth delivery and operation.
Common Pitfalls
#1Hardcoding URLs and credentials in test code
Wrong approach:cy.visit('https://staging.example.com') cy.get('#login').type('testUser')
Correct approach:cy.visit(Cypress.config('baseUrl')) cy.get('#login').type(Cypress.env('username'))
Root cause:Not separating environment data from test logic causes tests to break or leak data when environments change.
#2Setting environment variables only in config file without overrides
Wrong approach:// cypress.config.js module.exports = { env: { env: 'development' } }
Correct approach:// Use CLI or separate config files to override env per environment // e.g., cypress run --env env=staging
Root cause:Assuming static config is enough ignores the need for dynamic environment switching.
#3Storing production secrets in source-controlled config files
Wrong approach:// cypress.config.prod.js module.exports = { env: { password: 'prodSecret' } }
Correct approach:// Use CI environment variables or secret managers // Access via Cypress.env('password') at runtime
Root cause:Lack of security awareness leads to credential exposure and compliance risks.
Key Takeaways
Test configuration per environment lets the same tests run correctly in development, staging, and production by changing settings outside test code.
Cypress supports multiple ways to set environment variables and config files, which it merges in a specific order to determine final settings.
Separating environment data from test logic prevents errors, improves security, and makes tests reusable and maintainable.
Integrating environment config with CI pipelines automates testing across all stages, ensuring reliable software delivery.
Understanding config merging and override priorities helps avoid subtle bugs and enables advanced dynamic test setups.