Manuals / Cypress / Ch 8

C · StructureIntermediate60 min read

8. Page Object Model in Cypress

Cypress · 48 pages source format

POM in Cypress uses plain classes or modules — not inheritance magic. Encapsulate selectors and intent methods; keep specs as user stories.

What you'll learn

  • Page classes
  • Composition over deep hierarchies
  • cypress/e2e/pages/ layout

LoginPage class

Methods: visit(), login(user, pass), assertError(msg). Selectors private to the class.

class LoginPage {
  visit() { cy.visit("/"); }
  login(user, pass) {
    cy.get("[data-test=username]").type(user);
    cy.get("[data-test=password]").type(pass);
    cy.get("[data-test=login-button]").click();
  }
  assertError(msg) { cy.get("[data-test=error]").should("contain", msg); }
}
export default LoginPage;

Do this now

Create cypress/e2e/pages/LoginPage.js. Refactor login specs to use it.

Clear?

InventoryPage + CartPage

addItem(name), getCartCount(), proceedToCheckout() — specs read like scenarios.

Do this now

Build InventoryPage and CartPage. One spec: login → add 2 items → assert cart badge "2".

Clear?

Avoid over-abstraction

POM methods should match user intent, not every click. Three meaningful methods beat twenty one-liners.

Do this now

Review pages — merge methods that always run together.

Clear?

ARCHITECTURE.md

Document folder layout, naming, when to add a page vs a command.

Do this now

Write ARCHITECTURE.md with folder tree and conventions.

Clear?

Checklist