0
0
Cypresstesting~7 mins

Page Object Model in Cypress

Choose your learning style9 modes available
Introduction

The Page Object Model helps organize test code by separating page details from test steps. This makes tests easier to read and maintain.

When testing a website with many pages or complex user flows.
When you want to reuse code for interacting with the same page elements.
When you want to make your tests easier to update if the page changes.
When working in a team to keep test code consistent and clear.
Syntax
Cypress
class PageName {
  visit() {
    cy.visit('url')
  }

  getElement() {
    return cy.get('selector')
  }

  action() {
    this.getElement().click()
  }
}

export default PageName

Define a class for each page with methods for actions and elements.

Use cy.get() inside methods to locate elements.

Examples
This example shows a login page object with methods to visit the page, get fields, and perform login.
Cypress
class LoginPage {
  visit() {
    cy.visit('/login')
  }

  usernameField() {
    return cy.get('#username')
  }

  passwordField() {
    return cy.get('#password')
  }

  submitButton() {
    return cy.get('button[type="submit"]')
  }

  login(user, pass) {
    this.usernameField().type(user)
    this.passwordField().type(pass)
    this.submitButton().click()
  }
}

export default LoginPage
This test uses the LoginPage object to perform a login and check the URL after.
Cypress
import LoginPage from '../pages/LoginPage'

describe('Login Test', () => {
  const loginPage = new LoginPage()

  it('logs in successfully', () => {
    loginPage.visit()
    loginPage.login('user1', 'pass123')
    cy.url().should('include', '/dashboard')
  })
})
Sample Program

This test script defines a HomePage object with search functionality. The test visits the home page, performs a search, and verifies the URL contains the search term.

Cypress
class HomePage {
  visit() {
    cy.visit('/')
  }

  searchBox() {
    return cy.get('input[aria-label="Search"]')
  }

  searchButton() {
    return cy.get('button[type="submit"]')
  }

  search(text) {
    this.searchBox().type(text)
    this.searchButton().click()
  }
}

describe('Home Page Search Test', () => {
  const homePage = new HomePage()

  it('searches for a term', () => {
    homePage.visit()
    homePage.search('cypress')
    cy.url().should('include', 'search=cypress')
  })
})
OutputSuccess
Important Notes

Keep selectors simple and stable to avoid brittle tests.

Use meaningful method names to describe actions clearly.

Page objects help reduce duplicate code and improve test readability.

Summary

Page Object Model organizes page interactions into classes.

It makes tests easier to write, read, and maintain.

Use it to keep your Cypress tests clean and reusable.