0
0
Cypresstesting~15 mins

Page Object Model in Cypress - Build an Automation Script

Choose your learning style9 modes available
Login functionality using Page Object Model
Preconditions (2)
Step 1: Open the login page URL
Step 2: Enter 'testuser' in the username input field
Step 3: Enter 'Test@1234' in the password input field
Step 4: Click the login button
Step 5: Verify that the URL changes to 'https://example.com/dashboard'
Step 6: Verify that the dashboard heading 'Welcome, testuser!' is visible
✅ Expected Result: User is successfully logged in and redirected to the dashboard page with a welcome message.
Automation Requirements - Cypress
Assertions Needed:
URL should be 'https://example.com/dashboard' after login
Dashboard heading 'Welcome, testuser!' should be visible
Best Practices:
Use Page Object Model to separate page selectors and actions
Use Cypress commands and assertions consistently
Avoid hardcoded waits; use Cypress automatic waits
Use clear and descriptive method names in page objects
Automated Solution
Cypress
/// <reference types="cypress" />

// cypress/support/pageObjects/LoginPage.js
class LoginPage {
  visit() {
    cy.visit('https://example.com/login');
  }

  fillUsername(username) {
    cy.get('#username').clear().type(username);
  }

  fillPassword(password) {
    cy.get('#password').clear().type(password);
  }

  clickLogin() {
    cy.get('button[type="submit"]').click();
  }
}

export default LoginPage;


// cypress/integration/login_spec.js
import LoginPage from '../support/pageObjects/LoginPage';

describe('Login Test using Page Object Model', () => {
  const loginPage = new LoginPage();

  it('should login successfully with valid credentials', () => {
    loginPage.visit();
    loginPage.fillUsername('testuser');
    loginPage.fillPassword('Test@1234');
    loginPage.clickLogin();

    cy.url().should('eq', 'https://example.com/dashboard');
    cy.contains('h1', 'Welcome, testuser!').should('be.visible');
  });
});

The LoginPage class encapsulates all selectors and actions related to the login page. This keeps test code clean and easy to maintain.

The visit() method opens the login page URL. The fillUsername() and fillPassword() methods enter the credentials into the input fields. The clickLogin() method clicks the login button.

In the test file, we create an instance of LoginPage and call these methods in order. After clicking login, we assert that the URL is the dashboard URL and that the welcome heading is visible.

This structure follows the Page Object Model pattern, making tests easier to read and maintain.

Common Mistakes - 3 Pitfalls
Using selectors directly inside the test instead of page objects
Using hardcoded waits like cy.wait(5000)
Not clearing input fields before typing
Bonus Challenge

Now add data-driven testing with 3 different sets of username and password inputs using the Page Object Model.

Show Hint