0
0
Cypresstesting~15 mins

Headless mode in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify login functionality in headless mode
Preconditions (2)
Step 1: Open the login page URL
Step 2: Enter 'testuser' in the username input field with id 'username'
Step 3: Enter 'Test@1234' in 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 that the URL contains '/dashboard'
Step 7: Verify that the element with id 'welcomeMessage' contains text 'Welcome, testuser!'
✅ Expected Result: User is successfully logged in and redirected to the dashboard page with a welcome message displayed.
Automation Requirements - Cypress
Assertions Needed:
URL contains '/dashboard' after login
Welcome message contains 'Welcome, testuser!'
Best Practices:
Use explicit Cypress commands and assertions
Use data-test or id attributes for selectors
Run tests in headless mode using Cypress CLI
Avoid hardcoded waits; use Cypress automatic waits
Automated Solution
Cypress
describe('Login Test in Headless Mode', () => {
  it('should log in successfully and show welcome message', () => {
    cy.visit('https://example.com/login');
    cy.get('#username').type('testuser');
    cy.get('#password').type('Test@1234');
    cy.get('#loginBtn').click();
    cy.url().should('include', '/dashboard');
    cy.get('#welcomeMessage').should('contain.text', 'Welcome, testuser!');
  });
});

// To run this test in headless mode, use the command:
// npx cypress run --headless --spec 'cypress/e2e/login_spec.cy.js'

This Cypress test script automates the login process as described in the manual test case.

First, it visits the login page URL. Then it types the username and password into the input fields identified by their id attributes, which is a best practice for stable selectors.

After clicking the login button, it waits automatically for the page to load and verifies the URL contains /dashboard to confirm navigation.

Finally, it checks that the welcome message contains the expected text, confirming successful login.

The test is designed to run in headless mode by using the Cypress CLI command with the --headless flag, which runs the browser without opening a visible window, useful for automated pipelines.

Common Mistakes - 3 Pitfalls
Using hardcoded waits like cy.wait(5000) instead of relying on Cypress automatic waits
Using CSS selectors that are brittle or likely to change, like complex class names
{'mistake': 'Not specifying the headless mode in the test run command', 'why_bad': 'Tests run with the browser UI open, which is slower and not suitable for CI pipelines.', 'correct_approach': "Run tests with the command 'npx cypress run --headless' to execute tests without opening the browser window."}
Bonus Challenge

Now add data-driven testing with 3 different sets of valid username and password combinations.

Show Hint