Bird
Raised Fist0
Cypresstesting~15 mins

cypress.config.js settings - Deep Dive

Choose your learning style10 modes available
Overview - cypress.config.js settings
What is it?
cypress.config.js settings are configuration options that control how Cypress runs tests. This file tells Cypress things like which browser to use, where your tests live, and how long to wait for things. It is a simple JavaScript file that exports an object with these settings. Beginners can change this file to customize their test runs without changing test code.
Why it matters
Without cypress.config.js settings, Cypress would run with default options that might not fit your project needs. You would waste time changing tests or running tests in the wrong environment. This file solves the problem of flexible, repeatable test runs that match your project setup. It helps teams run tests consistently and catch bugs faster.
Where it fits
Before learning cypress.config.js settings, you should know basic Cypress test writing and how to run tests. After this, you can learn advanced Cypress plugins, custom commands, and CI/CD integration to automate tests fully.
Mental Model
Core Idea
cypress.config.js is the central control panel that tells Cypress how to run your tests exactly the way you want.
Think of it like...
It's like setting the thermostat and timer on your oven before baking a cake — you decide the temperature, time, and mode so the cake bakes perfectly every time.
┌─────────────────────────────┐
│       cypress.config.js      │
├─────────────┬───────────────┤
│ Setting     │ Description   │
├─────────────┼───────────────┤
│ baseUrl     │ Starting URL  │
│ viewport    │ Window size   │
│ retries     │ Test retries  │
│ e2e         │ Test folder   │
│ video       │ Record tests? │
└─────────────┴───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is cypress.config.js file
🤔
Concept: Introduce the configuration file that controls Cypress test runs.
cypress.config.js is a JavaScript file in your project root. It exports an object with settings that Cypress reads before running tests. This file replaces older cypress.json files and supports modern JavaScript syntax.
Result
You have a file ready to customize how Cypress behaves for your project.
Understanding that Cypress uses a single config file to control test behavior helps you avoid changing tests for environment differences.
2
FoundationBasic structure of cypress.config.js
🤔
Concept: Learn the syntax and main parts of the config file.
The file exports defineConfig({ ... }) from 'cypress' package. Inside, you set keys like e2e, component, baseUrl, viewportWidth, etc. For example: import { defineConfig } from 'cypress' export default defineConfig({ e2e: { baseUrl: 'http://localhost:3000', specPattern: 'cypress/e2e/**/*.cy.js', supportFile: 'cypress/support/e2e.js' }, viewportWidth: 1280, viewportHeight: 720 })
Result
You can write a valid config file that Cypress understands and uses.
Knowing the file structure and syntax prevents syntax errors and lets you customize settings confidently.
3
IntermediateConfiguring test folders and spec patterns
🤔Before reading on: do you think Cypress runs all files in the project folder by default or only specific test files? Commit to your answer.
Concept: Learn how to tell Cypress where your tests live and which files to run.
In the e2e object, specPattern defines which test files Cypress runs. You can use glob patterns like 'cypress/e2e/**/*.cy.js' to include all .cy.js files in subfolders. supportFile points to code that runs before tests, like commands or setup. Changing these lets you organize tests your way.
Result
Cypress runs only the tests you want, improving speed and clarity.
Understanding spec patterns helps you control test scope and avoid running unwanted files.
4
IntermediateSetting baseUrl and viewport size
🤔Before reading on: does setting baseUrl affect how you write test URLs? Commit to your answer.
Concept: Learn how to set the starting URL and browser window size for tests.
baseUrl lets you write shorter test commands like cy.visit('/') instead of full URLs. viewportWidth and viewportHeight set the browser window size, simulating different devices. For example, viewportWidth: 375 and viewportHeight: 667 simulates a phone screen.
Result
Tests run faster with baseUrl and simulate real user screens with viewport settings.
Knowing baseUrl simplifies test code and viewport settings help catch layout bugs on different devices.
5
IntermediateConfiguring retries and timeouts
🤔Before reading on: do you think retries make tests slower or more reliable? Commit to your answer.
Concept: Learn how to make tests retry on failure and adjust waiting times.
retries setting tells Cypress how many times to rerun a failing test before marking it failed. defaultCommandTimeout sets how long Cypress waits for commands like clicking or typing. Adjusting these helps tests pass in flaky environments or slow apps.
Result
Tests become more stable and less flaky in real-world conditions.
Understanding retries and timeouts helps balance test speed and reliability.
6
AdvancedUsing environment variables in config
🤔Before reading on: do you think environment variables in config are static or can change per run? Commit to your answer.
Concept: Learn how to use env object to pass variables to tests dynamically.
The env key in config lets you define variables accessible in tests via Cypress.env('key'). You can set API keys, feature flags, or URLs here. These can be overridden by CLI or CI environment variables for flexible runs.
Result
Tests adapt to different environments without code changes.
Knowing env usage enables secure and flexible test configurations across environments.
7
ExpertDynamic config with function and plugins
🤔Before reading on: can cypress.config.js export a function to change config at runtime? Commit to your answer.
Concept: Learn how to export a function or use plugins to modify config dynamically.
Instead of exporting a static object, you can export a function that returns config based on environment variables or other logic. Also, plugins can modify config before tests run. This allows complex setups like different configs per branch or test type.
Result
You gain full control over test configuration adapting to complex workflows.
Understanding dynamic config unlocks powerful customization for large projects and CI pipelines.
Under the Hood
When Cypress starts, it loads cypress.config.js and reads the exported configuration object. This config controls the test runner's behavior, including which tests to run, browser settings, timeouts, and environment variables. Cypress merges this config with CLI options and environment variables, resolving conflicts by priority. The config is then passed to the internal test runner engine, which uses it to launch browsers, find test files, and execute commands accordingly.
Why designed this way?
Cypress moved from cypress.json to cypress.config.js to allow more flexibility using JavaScript syntax. This lets users write dynamic configs, import modules, and use modern JS features. The design balances simplicity for beginners with power for advanced users. Alternatives like static JSON files were too limited for complex projects and CI/CD pipelines.
┌───────────────────────────────┐
│       cypress.config.js        │
│  (exports config object)       │
└──────────────┬────────────────┘
               │
               ▼
┌───────────────────────────────┐
│ Cypress Test Runner Engine     │
│ - Reads config                │
│ - Merges CLI/env overrides    │
│ - Launches browser            │
│ - Runs tests                  │
└──────────────┬────────────────┘
               │
               ▼
┌───────────────────────────────┐
│ Browser & Test Execution       │
│ - Opens browser window        │
│ - Executes test commands      │
│ - Reports results             │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does changing cypress.config.js require restarting Cypress to take effect? Commit to yes or no.
Common Belief:People often think changes to cypress.config.js apply immediately without restarting.
Tap to reveal reality
Reality:Cypress needs to be restarted to load new config settings; otherwise, old settings persist during the session.
Why it matters:Not restarting leads to confusion when config changes seem ignored, wasting debugging time.
Quick: Do you think baseUrl must be a full URL including protocol? Commit to yes or no.
Common Belief:Some believe baseUrl can be just a domain or path without protocol.
Tap to reveal reality
Reality:baseUrl must be a full URL with protocol (http:// or https://) for Cypress to work correctly.
Why it matters:Incorrect baseUrl causes tests to fail visiting pages, blocking test runs.
Quick: Does setting retries guarantee tests will always pass eventually? Commit to yes or no.
Common Belief:People think retries fix all flaky tests automatically.
Tap to reveal reality
Reality:Retries help with intermittent failures but do not fix underlying test or app bugs.
Why it matters:Overusing retries hides real problems and delays fixing flaky tests.
Quick: Can you use cypress.config.js to configure test code behavior directly? Commit to yes or no.
Common Belief:Some believe config can change test logic or assertions directly.
Tap to reveal reality
Reality:Config only controls test runner behavior, not test code logic itself.
Why it matters:Misunderstanding this leads to trying to fix test failures by changing config instead of test code.
Expert Zone
1
Some config options behave differently in component testing vs end-to-end testing, requiring separate e2e and component keys.
2
Environment variables set in config can be overridden by CLI or CI environment variables, with a clear priority order.
3
Dynamic config functions can return promises, allowing asynchronous config loading before tests start.
When NOT to use
Avoid overloading cypress.config.js with complex logic or secrets; use environment variables or separate config files for sensitive data. For very dynamic test setups, consider using Cypress plugins or external scripts instead of complex config functions.
Production Patterns
Teams use cypress.config.js to set different baseUrls per environment (dev, staging, prod) via environment variables. They configure retries and timeouts to stabilize flaky tests in CI. Also, they separate e2e and component test configs for clarity and performance.
Connections
Environment Variables
builds-on
Understanding how cypress.config.js uses environment variables helps manage secrets and dynamic test settings securely across environments.
Continuous Integration (CI)
builds-on
Knowing cypress.config.js settings is essential to configure tests that run reliably and efficiently in automated CI pipelines.
Software Configuration Management
same pattern
cypress.config.js exemplifies how software tools use configuration files to separate setup from code, a pattern common in many software systems.
Common Pitfalls
#1Not restarting Cypress after changing config causes old settings to persist.
Wrong approach:Change cypress.config.js and immediately run tests without restart.
Correct approach:After changing cypress.config.js, close and reopen Cypress test runner to load new config.
Root cause:Cypress loads config only at startup, so changes are ignored until restart.
#2Setting baseUrl without protocol leads to test failures.
Wrong approach:baseUrl: 'localhost:3000',
Correct approach:baseUrl: 'http://localhost:3000',
Root cause:Cypress requires full URLs including protocol to navigate correctly.
#3Using retries to mask flaky tests instead of fixing them.
Wrong approach:retries: { runMode: 3, openMode: 3 }, // blindly retry all failures
Correct approach:Use retries sparingly and investigate flaky tests to fix root causes.
Root cause:Misunderstanding retries as a fix rather than a temporary workaround.
Key Takeaways
cypress.config.js is the main file to customize how Cypress runs tests, controlling browsers, test locations, and timeouts.
Using baseUrl and viewport settings simplifies test code and simulates real user environments.
Retries and timeouts improve test stability but should not replace fixing flaky tests.
Environment variables in config enable flexible, secure test runs across different environments.
Advanced users can write dynamic config functions for complex workflows and CI integration.

Practice

(1/5)
1. What is the main purpose of the cypress.config.js file in a Cypress project?
easy
A. To set configuration options like base URL and test locations for Cypress tests
B. To write the actual test cases for Cypress
C. To install Cypress dependencies
D. To run Cypress tests manually from the command line

Solution

  1. Step 1: Understand the role of cypress.config.js

    This file is used to configure how Cypress runs tests, including settings like base URL and test file paths.
  2. Step 2: Differentiate from other files

    Test cases are written in separate test files, not in the config file. Installation and running commands happen outside this file.
  3. Final Answer:

    To set configuration options like base URL and test locations for Cypress tests -> Option A
  4. Quick Check:

    Config file sets options = D [OK]
Hint: Config file sets test environment and paths [OK]
Common Mistakes:
  • Confusing config file with test files
  • Thinking config installs Cypress
  • Believing config runs tests manually
2. Which of the following is the correct way to export the Cypress configuration using defineConfig in cypress.config.js?
easy
A. module.exports = { baseUrl: 'http://localhost:3000' }
B. export const config = { baseUrl: 'http://localhost:3000' }
C. defineConfig({ baseUrl: 'http://localhost:3000' })
D. export default defineConfig({ e2e: { baseUrl: 'http://localhost:3000' } })

Solution

  1. Step 1: Recall the modern Cypress config syntax

    Since Cypress 10+, the config file uses defineConfig and exports it as default with ES module syntax.
  2. Step 2: Check the correct structure

    The e2e object wraps settings like baseUrl. export default defineConfig({ e2e: { baseUrl: 'http://localhost:3000' } }) matches this pattern exactly.
  3. Final Answer:

    export default defineConfig({ e2e: { baseUrl: 'http://localhost:3000' } }) -> Option D
  4. Quick Check:

    Use defineConfig with export default = B [OK]
Hint: Use export default defineConfig({ e2e: { ... } }) [OK]
Common Mistakes:
  • Forgetting to wrap settings inside e2e object
  • Using CommonJS export instead of ES module
  • Not using defineConfig function
3. Given this cypress.config.js snippet, what will be the base URL used during test runs?
import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    baseUrl: 'https://example.com',
    specPattern: 'cypress/e2e/**/*.cy.js'
  }
})
medium
A. http://localhost:3000
B. https://example.com
C. cypress/e2e/**/*.cy.js
D. No base URL is set

Solution

  1. Step 1: Identify the baseUrl property in config

    The config sets baseUrl to 'https://example.com' inside the e2e object.
  2. Step 2: Understand baseUrl usage

    This URL is used as the root for all relative URLs in tests, so it will be 'https://example.com'.
  3. Final Answer:

    https://example.com -> Option B
  4. Quick Check:

    baseUrl set to https://example.com = C [OK]
Hint: Look for baseUrl inside e2e object [OK]
Common Mistakes:
  • Confusing specPattern with baseUrl
  • Assuming default localhost URL
  • Missing that baseUrl is inside e2e
4. You wrote this cypress.config.js but Cypress throws an error when running tests:
import { defineConfig } from 'cypress'

export default {
  e2e: {
    baseUrl: 'http://localhost:8080'
  }
}
What is the likely cause of the error?
medium
A. Using export default instead of module.exports
B. baseUrl must be outside the e2e object
C. Missing call to defineConfig wrapping the config object
D. baseUrl value must be an IP address

Solution

  1. Step 1: Check the export syntax

    The config is exported as a plain object, but Cypress expects the config wrapped in defineConfig().
  2. Step 2: Understand Cypress config requirements

    Without defineConfig, Cypress cannot properly parse the config, causing errors.
  3. Final Answer:

    Missing call to defineConfig wrapping the config object -> Option C
  4. Quick Check:

    Always wrap config in defineConfig() = A [OK]
Hint: Always wrap config object with defineConfig() [OK]
Common Mistakes:
  • Placing baseUrl outside e2e
  • Confusing export default with CommonJS
  • Thinking baseUrl must be IP address
5. You want to set a custom environment variable API_KEY in cypress.config.js so it can be accessed in your tests. Which is the correct way to add it inside the config?
hard
A. export default defineConfig({ e2e: { env: { API_KEY: '12345' } } })
B. export default defineConfig({ env: { API_KEY: '12345' } })
C. export default defineConfig({ e2e: { baseUrl: 'http://localhost', API_KEY: '12345' } })
D. export default defineConfig({ e2e: { environment: { API_KEY: '12345' } } })

Solution

  1. Step 1: Locate where environment variables go

    Environment variables for e2e tests go inside the env object nested within the e2e config.
  2. Step 2: Verify correct property names

    The key must be env, not environment, and it must be inside e2e.
  3. Final Answer:

    export default defineConfig({ e2e: { env: { API_KEY: '12345' } } }) -> Option A
  4. Quick Check:

    Use e2e.env for env vars = A [OK]
Hint: Put env vars inside e2e.env object [OK]
Common Mistakes:
  • Placing env outside e2e
  • Using wrong key name like environment
  • Adding env vars directly under e2e without env object
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard