Bird
Raised Fist0
Cypresstesting~15 mins

Test configuration per environment in Cypress - Build an Automation Script

Choose your learning style10 modes available
Verify login functionality using environment-specific configuration
Preconditions (3)
Step 1: Set Cypress environment to 'development'
Step 2: Open the login page using the base URL from the 'development' environment configuration
Step 3: Enter username 'devUser' in the username field
Step 4: Enter password 'devPass123' in the password field
Step 5: Click the login button
Step 6: Verify that the URL contains '/dashboard' indicating successful login
Step 7: Set Cypress environment to 'production'
Step 8: Open the login page using the base URL from the 'production' environment configuration
Step 9: Enter username 'prodUser' in the username field
Step 10: Enter password 'prodPass123' in the password field
Step 11: Click the login button
Step 12: Verify that the URL contains '/dashboard' indicating successful login
✅ Expected Result: The login succeeds in both environments using the correct base URL and credentials, and the user is redirected to the dashboard page.
Automation Requirements - Cypress
Assertions Needed:
Verify URL contains '/dashboard' after login in each environment
Best Practices:
Use Cypress environment variables to manage base URLs and credentials
Use cy.visit() with environment-specific base URL
Use data-test attributes or stable selectors for locating elements
Avoid hardcoding URLs or credentials in test code
Use beforeEach hook to set up test preconditions
Keep tests isolated and repeatable
Automated Solution
Cypress
/// <reference types="cypress" />

describe('Login tests per environment', () => {
  const environments = [
    {
      name: 'development',
      baseUrl: Cypress.env('devBaseUrl'),
      username: Cypress.env('devUsername'),
      password: Cypress.env('devPassword')
    },
    {
      name: 'production',
      baseUrl: Cypress.env('prodBaseUrl'),
      username: Cypress.env('prodUsername'),
      password: Cypress.env('prodPassword')
    }
  ];

  environments.forEach(({ name, baseUrl, username, password }) => {
    context(`Login test on ${name} environment`, () => {
      beforeEach(() => {
        cy.visit(baseUrl + '/login');
      });

      it('should login successfully and redirect to dashboard', () => {
        cy.get('[data-test=username]').clear().type(username);
        cy.get('[data-test=password]').clear().type(password);
        cy.get('[data-test=login-button]').click();

        cy.url().should('include', '/dashboard');
      });
    });
  });
});

This test script uses Cypress to automate login tests for two environments: development and production.

We define an array environments holding the environment name, base URL, username, and password. These values come from Cypress environment variables, so no sensitive data is hardcoded.

For each environment, we create a test context. Before each test, we visit the login page using the environment's base URL.

The test enters the username and password into fields identified by data-test attributes, clicks the login button, and asserts that the URL includes /dashboard to confirm successful login.

This approach keeps tests clean, reusable, and environment-aware.

Common Mistakes - 4 Pitfalls
Hardcoding URLs and credentials directly in the test code
Using brittle selectors like CSS classes or element indexes
Not waiting for page load or elements before interacting
Mixing environment logic inside test steps instead of parameterizing
Bonus Challenge

Now add data-driven testing with 3 different sets of user credentials per environment to verify login success and failure cases.

Show Hint

Practice

(1/5)
1. What is the main purpose of setting baseUrl in Cypress configuration for different environments?
easy
A. To change the test framework version automatically
B. To run tests against different websites without changing test code
C. To enable debugging mode in tests
D. To set the timeout for all tests

Solution

  1. Step 1: Understand baseUrl role

    baseUrl defines the main website address for tests to run against.
  2. Step 2: Relate baseUrl to environment

    Setting different baseUrl values per environment lets tests run on different sites without changing test code.
  3. Final Answer:

    To run tests against different websites without changing test code -> Option B
  4. Quick Check:

    baseUrl changes target site = A [OK]
Hint: baseUrl points tests to the right website per environment [OK]
Common Mistakes:
  • Confusing baseUrl with test timeout
  • Thinking baseUrl changes test framework version
  • Assuming baseUrl enables debugging
2. Which of the following is the correct way to access an environment variable named apiKey inside a Cypress test?
easy
A. const key = Cypress.env('apiKey')
B. const key = Cypress.get('apiKey')
C. const key = Cypress.config('apiKey')
D. const key = Cypress.variable('apiKey')

Solution

  1. Step 1: Recall method to get env variables

    Cypress provides Cypress.env() to access environment variables.
  2. Step 2: Match method with variable name

    Using Cypress.env('apiKey') correctly retrieves the apiKey value.
  3. Final Answer:

    const key = Cypress.env('apiKey') -> Option A
  4. Quick Check:

    Cypress.env() gets env vars = C [OK]
Hint: Use Cypress.env('varName') to get environment variables [OK]
Common Mistakes:
  • Using Cypress.config() instead of Cypress.env()
  • Trying Cypress.get() which does not exist
  • Using Cypress.variable() which is invalid
3. Given this cypress.config.js snippet:
export default defineConfig({
  env: {
    username: 'user1',
    password: 'pass1'
  }
})

What will console.log(Cypress.env('username')) print during a test?
medium
A. null
B. 'username'
C. 'user1'
D. undefined

Solution

  1. Step 1: Check env object in config

    The config sets env.username to 'user1'.
  2. Step 2: Understand Cypress.env() behavior

    Cypress.env('username') returns the value of the username key from env, which is 'user1'.
  3. Final Answer:

    'user1' -> Option C
  4. Quick Check:

    Env username value = 'user1' [OK]
Hint: Cypress.env('key') returns the value set in config env [OK]
Common Mistakes:
  • Expecting the key name instead of its value
  • Assuming undefined if not set in test code
  • Confusing Cypress.env() with Cypress.config()
4. You wrote this in cypress.config.js:
env: {
  apiUrl: 'https://api.example.com'
}

But inside your test, Cypress.env('apiUrl') returns undefined. What is the most likely cause?
medium
A. The env object is not inside the exported config
B. You forgot to export the config object
C. You must use process.env instead
D. Cypress.env() only works for baseUrl

Solution

  1. Step 1: Check config structure

    The env object must be inside the exported config object for Cypress to read it.
  2. Step 2: Identify common mistake

    If env is outside or not properly nested, Cypress.env() returns undefined.
  3. Final Answer:

    The env object is not inside the exported config -> Option A
  4. Quick Check:

    env must be inside exported config = B [OK]
Hint: Always nest env inside exported config object [OK]
Common Mistakes:
  • Not exporting the config at all
  • Using process.env instead of Cypress.env
  • Thinking Cypress.env only works for baseUrl
5. You want to run tests on two environments: staging and production. You set baseUrl and env.apiKey differently for each in cypress.config.js. How can you run tests on staging without changing the config file each time?
hard
A. Use cy.visit() with full URL every time
B. Manually edit cypress.config.js before each run
C. Set baseUrl and env inside each test file
D. Use command line flag like cypress run --env configFile=staging and load config accordingly

Solution

  1. Step 1: Understand environment config switching

    You can pass environment variables or flags via command line to select config variants.
  2. Step 2: Use command line flag to select config

    Using --env configFile=staging lets you load staging config without editing files.
  3. Final Answer:

    Use command line flag like cypress run --env configFile=staging and load config accordingly -> Option D
  4. Quick Check:

    Command line env flags switch configs = A [OK]
Hint: Use CLI flags to pick environment config dynamically [OK]
Common Mistakes:
  • Editing config file manually each time
  • Hardcoding URLs inside tests
  • Ignoring CLI environment options
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