0
0
Cypresstesting~15 mins

Environment variables for configuration in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify login functionality using environment variables for credentials
Preconditions (2)
Step 1: Open the login page URL
Step 2: Enter the email from environment variable 'CYPRESS_USER_EMAIL' into the email input field with id 'email'
Step 3: Enter the password from environment variable 'CYPRESS_USER_PASSWORD' into the password input field with id 'password'
Step 4: Click the login button with id 'loginBtn'
Step 5: Wait for the dashboard page to load
Step 6: Verify the URL contains '/dashboard'
Step 7: Verify the page contains a welcome message with id 'welcomeMessage'
✅ Expected Result: User is successfully logged in and redirected to the dashboard page with a visible welcome message
Automation Requirements - Cypress
Assertions Needed:
URL contains '/dashboard'
Element with id 'welcomeMessage' is visible
Best Practices:
Use Cypress environment variables accessed via Cypress.env()
Use explicit Cypress commands with proper selectors
Avoid hardcoding credentials in test code
Use beforeEach hook to visit the login page
Use clear and maintainable selectors (id preferred)
Automated Solution
Cypress
describe('Login Test Using Environment Variables', () => {
  beforeEach(() => {
    cy.visit('https://example.com/login');
  });

  it('should login successfully using env variables', () => {
    const email = Cypress.env('USER_EMAIL');
    const password = Cypress.env('USER_PASSWORD');

    cy.get('#email').type(email);
    cy.get('#password').type(password, { log: false });
    cy.get('#loginBtn').click();

    cy.url().should('include', '/dashboard');
    cy.get('#welcomeMessage').should('be.visible');
  });
});

This test suite uses Cypress to automate login using environment variables for credentials.

The beforeEach hook opens the login page before each test.

Inside the test, Cypress.env() fetches the email and password securely without hardcoding them.

Selectors use id attributes for clarity and reliability.

The password input uses { log: false } to avoid showing sensitive data in logs.

Assertions check that the URL contains '/dashboard' and the welcome message is visible, confirming successful login.

Common Mistakes - 4 Pitfalls
Hardcoding credentials directly in the test code
Using non-unique or fragile selectors like XPath or complex CSS selectors
Not waiting for page navigation before asserting URL or elements
Logging sensitive information like passwords in test output
Bonus Challenge

Now add data-driven testing with 3 different sets of environment variables for login credentials

Show Hint