Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 35 ยท Structure and Maintainability

Page Objects and Better Test Structure

Structure browser tests with page objects, component objects and app actions, and learn when abstraction helps and when it only gets in the way.

A test suite is code, and like all code it rots if nobody organizes it. The usual symptom is a selector like #btn-login copied into forty tests. When a developer renames that button, forty tests fail for a reason that has nothing to do with login. The fix is to give each piece of the user interface one home in your test code. The best-known pattern for that is the page object.

Cypress and Playwright cannot run on this site, so the real code below is read-only. The runnable examples are stand-ins: a small fake application and a fake driver written in plain JavaScript, so you can see a messy test refactored and watch the benefit in numbers. The structure itself is real and works the same in both tools.

The problem: tests that know too much

Here is a test written in a hurry. Every selector and every step is inline.

JavaScript
// Cypress (read-only)
it('logs in', () => {
  cy.visit('/login')
  cy.get('#email').type('[email protected]')
  cy.get('#pw').type('secret')
  cy.get('#go').click()
  cy.get('.welcome h2').should('contain', 'Hello, Ada')
})

it('rejects a wrong password', () => {
  cy.visit('/login')
  cy.get('#email').type('[email protected]')
  cy.get('#pw').type('nope')
  cy.get('#go').click()
  cy.get('.error').should('contain', 'Wrong password')
})

Each test mixes what the user wants (log in) with how the page is built (ids and class names). Two costs follow: the tests are hard to read, and every markup change touches many files.

Page objects

A page object is a small class or module that represents one page (or one big area) of the app. It owns the selectors and exposes methods named after what the user can do.

TypeScript
// Playwright (read-only): login-page.ts
import { type Page, type Locator, expect } from '@playwright/test';

export class LoginPage {
  readonly email: Locator;
  readonly password: Locator;
  readonly submit: Locator;
  readonly error: Locator;

  constructor(private readonly page: Page) {
    this.email = page.getByLabel('Email');
    this.password = page.getByLabel('Password');
    this.submit = page.getByRole('button', { name: 'Sign in' });
    this.error = page.getByRole('alert');
  }

  async open() {
    await this.page.goto('/login');
  }

  async signIn(email: string, password: string) {
    await this.email.fill(email);
    await this.password.fill(password);
    await this.submit.click();
  }
}
TypeScript
// Playwright (read-only): login.spec.ts
test('rejects a wrong password', async ({ page }) => {
  const login = new LoginPage(page);
  await login.open();
  await login.signIn('[email protected]', 'nope');
  await expect(login.error).toHaveText('Wrong password');
});

Notice two design choices. The page object does not contain the expect for the scenario; the test keeps its assertions, so you can see what it checks. And the methods are phrased in user terms (signIn), not in implementation terms (clickSubmitButton).

In Cypress the same idea works with plain objects and functions that return chains:

JavaScript
// Cypress (read-only): cypress/support/pages/login.js
export const loginPage = {
  email: () => cy.get('[data-cy=email]'),
  password: () => cy.get('[data-cy=password]'),
  submit: () => cy.contains('button', 'Sign in'),
  open() { cy.visit('/login') },
  signIn(email, password) {
    this.email().type(email)
    this.password().type(password, { log: false })
    this.submit().click()
  },
}

Note that the selectors are functions. A Cypress chain starts when cy.get runs; storing an element in a variable would not work (the reason is explained in How Cypress Commands Really Work). Playwright locators, by contrast, are lazy descriptions and are safe to create early and keep.

Refactoring a messy test, step by step

The stand-in below has a fake app that exists in two versions. In version 1 the form uses short ids. In version 2 the team switched to data-test attributes. Three tests are written the messy way, three the page-object way, and both groups are run against each version. Then we count what had to change.

JS Messy tests versus a page object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The redesign breaks both groups equally, as it should: the selectors really did change. The difference is the cost of the repair. The page-object tests are fixed by editing the selectors object once, while the messy tests would each need to be opened and edited. With three tests that is a minor inconvenience; with three hundred it decides whether anyone keeps the suite alive.

Component objects

Not every reusable piece is a whole page. A site header, a modal dialog, a data table and a date picker appear on many pages. Give them their own component objects, constructed with a root locator, and let page objects hold them:

TypeScript
// Playwright (read-only)
class CartDrawer {
  constructor(private readonly root: Locator) {}
  item(name: string) { return this.root.getByRole('listitem').filter({ hasText: name }); }
  async remove(name: string) {
    await this.item(name).getByRole('button', { name: 'Remove' }).click();
  }
}

class ShopPage {
  readonly cart = new CartDrawer(this.page.getByRole('complementary', { name: 'Cart' }));
  constructor(private readonly page: Page) {}
}

Scoping everything to a root keeps selectors short and prevents a match in some other part of the page.

App actions: skip the UI when the UI is not the test

Page objects tidy up how you drive the UI. But many tests do not care about the UI for their setup. A test of the cart total does not need to click through registration, search and product pages first. App actions set up state without the interface: an API request, a test-only endpoint, or a database seed.

TypeScript
// Playwright (read-only)
test('shows the cart total', async ({ page, request }) => {
  await request.post('/api/test/cart', { data: { items: ['pen', 'ink'] } });
  await page.goto('/cart');
  await expect(page.getByTestId('total')).toHaveText('$12.00');
});

The stand-in below counts the steps. It builds a cart through the fake "UI" and through an app action, then runs the same check.

JS UI setup versus an app action

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Keep at least one test that builds the cart through the real UI, since that journey is also worth protecting. All the other tests can take the shortcut. Test Data and Logging In Fast covers this approach in depth.

flowchart TD
  T["Test<br/>states intent and assertions"] --> P["Page object<br/>one page or area"]
  P --> C["Component objects<br/>header, modal, table"]
  T --> A["App actions<br/>API or seed for setup"]
  P --> U["Browser UI"]
  C --> U
  A --> S["Server and database"]

Tests describe intent. Page and component objects wrap the interface, and app actions bypass it for setup.

When abstraction helps and when it hurts

Page objects are a tool, not a rule. Use them when a page is touched by many tests and its markup may change. They hurt when:

  • One object per page for a suite of five tests. A helper class that wraps a single cy.get adds a file to open and nothing else.
  • Methods hide the assertions. If loginPage.verifyEverythingWorks() checks six things, a failure tells you little.
  • Deep inheritance. BasePage extended by FormPage extended by LoginPage is hard to read. Prefer small objects and composition.
  • Methods that mirror the DOM (clickButton3) instead of intent (signIn).

Some naming habits keep the structure tidy: files named after the page (login-page.ts), methods that start with a verb (open, signIn, removeItem), getters or locators named after the thing (error, total), and a clear rule that assertions stay in tests. Fixtures from Hooks, Fixtures and Custom Commands are a good way to hand ready-made page objects to tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main goal of a page object?

    A page object centralizes how a page is driven, so a markup change is fixed in one file instead of many tests.
  2. 2. Where should the assertions for a scenario normally live?

    Keeping assertions in the test keeps intent visible. Helpers can expose elements and actions, and the test decides what to check.
  3. 3. In Cypress, why are page object selectors usually written as functions?

    Cypress commands are queued when called. A function creates a fresh chain each time it is used.
  4. 4. A test checks the cart total only. What is the best way to build its starting state?

    App actions keep unrelated UI journeys out of the test, which makes it faster and less likely to fail for unrelated reasons.
  5. 5. Which is a sign of over-abstraction?

    Deep hierarchies and thin wrappers make a suite harder to read. Prefer small objects and composition.

Summary

  • Put each page's or component's selectors and steps in one place so markup changes are cheap to fix.
  • Name methods after user intent and keep assertions in the tests.
  • In Cypress, expose selectors as functions; Playwright locators are lazy and safe to store.
  • Component objects model reusable pieces such as headers, modals and tables.
  • App actions (API calls or seeds) replace long UI setup; keep one real UI journey as well.
  • Avoid thin wrappers, hidden assertions and deep inheritance.

Next: Configuration and Environments