QA Interview Hub · Knowledge base · Quizzes · Українська

Patterns

Page Object Model

What problem Page Object solves

A Page Object moves a screen's locators and actions into one class, so a layout change needs a fix in one place. The idea is to separate the reasons for change: the scenario changes with product behaviour, locators with the layout. For few tests a helper function may be enough, and a class per URL is not the goal: the boundary is a logical screen, a form or a modal.

Patterns · Page Object

The button «Sign in» was renamed to «Log in» and 40 tests failed. How many lines to fix?

A designer renamed the login button. Every test that finds it by role and name went red: 40 files, each with the same three lines of fill and click. One change, 40 places to touch, and the next rename will repeat it. This lesson explains what problem Page Object solves, why it is built this way and where its limits are.

How it works and why. A Page Object (POM) is a class that describes a screen in the user's language. It holds locators ("where the elements are") and actions ("what is done with them"). The test says what to do ("log in") and the class knows how. The idea is to separate the reasons for change: a business scenario changes when product behaviour changes, while locators and the order of clicks change when the markup changes. Markup changes far more often. If both layers live in one place, every UI edit touches every test. If they are separated, a markup edit touches one file.

Where the knowledge about a page lives

Test 1Test 2Test 3LoginPagelocators: email, submitactions: goto(), login()The /login page
Figure 1. All tests reach the page through one class. The button name changed: one line in LoginPage is fixed.

This is especially convenient in Playwright because a Locator is lazy: it describes how to find an element but searches for nothing at the moment of creation. Search and waiting happen only on an action or an assertion. So it is safe to create locators in the constructor even when the page is not open yet, and a Page Object needs no "initialisation" before use.

const loginPage = new LoginPage(page);
// page is still about:blank, yet no error: the Locator searched for nothing
await loginPage.goto();
await loginPage.submit.click(); // it searches and waits here

Example: from 40 copies to one line. The starting point: every test knows by itself how the form works.

test('login: success', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill('qa@test.com');
  await page.getByLabel('Password').fill('secret');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page).toHaveURL('/dashboard');
});

test('login: wrong password', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill('qa@test.com');
  await page.getByLabel('Password').fill('wrong');
  await page.getByRole('button', { name: 'Sign in' }).click();
  // 38 more files with the same three lines
});

Each test reads fine on its own. The problem is scale: the knowledge "the button is called Sign in" is copied to every file. After the rename each of them fails with a timeout because the locator found nothing, and the cause is the same in all forty reports. Now the same knowledge gathered in one class:

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

  constructor(private readonly page: Page) {
    this.email = page.getByLabel('Email');
    this.password = page.getByLabel('Password');
    // the only place that knows the button name
    this.submit = page.getByRole('button', { name: 'Log in' });
  }

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

  async login(email: string, password: string) {
    await this.email.fill(email);
    await this.password.fill(password);
    await this.submit.click();
  }
}

The test loses the mechanics and keeps the scenario:

test('login: success', async ({ page }) => {
  const loginPage = new LoginPage(page);
  await loginPage.goto();
  await loginPage.login('qa@test.com', 'secret');
  await expect(page).toHaveURL('/dashboard');
});

Now renaming the button is an edit in the line with submit, and none of the 40 tests changes. This answers the temptation to fix everything with find and replace across files: it works only on an exact string match, does not cure the cause and has to be repeated at the next change. A Page Object moves the knowledge to one place, so the edit is made once.

Where to edit when the button changed

Wrong

Locators scattered across tests

Renaming the button: 40 edits and 40 chances to miss one. Tests read as a list of clicks.

Right

The locator in one class

An edit in one line. The test names the action: loginPage.login(user), the mechanics stay inside.

Figure 2. A Page Object does not make locators better, it gathers the knowledge about a page in one place.

Where the limits of Page Object are. POM is not "a class per URL". The boundary is set by meaning: a logical screen, a complex form, a modal. A header repeated on every page is better extracted into a separate component than duplicated in all classes (see the lesson on Page Component). A Page Object does not cure unstable tests: a bad locator in a class stays bad, it is just easier to find. It adds a layer of indirection: to understand a test, the reader opens one more file. For five to ten tests on one page that layer may not pay off, and a plain login(page, user) function is enough. So Page Object is not a dogma but a way to keep markup changes in one place once there are many tests. Alternatives that often complement it: Playwright fixtures (they create the needed class), Screenplay (tasks and actors instead of pages) and simple helper functions.

Common mistakes.

  • A class per URL regardless of meaning: dozens of empty classes while the real logic is smeared around. Consequence: the same problems plus extra bureaucracy.
  • A test bypasses the Page Object and uses page.locator directly: a locator change again touches several places and the benefit is gone.
  • Building the same locator in several methods instead of one field: the copies drift apart.
  • Methods named by mechanics (clickSubmitButton) rather than intent: the name breaks together with the markup and the test does not read as a scenario.

Check yourself

A test creates new LoginPage(page) before calling page.goto(). Is there an error if the constructor builds locators with page.getByLabel('Email')?

Answer

No error. getByLabel only describes a search and looks for nothing in the DOM. The element is resolved during fill() or expect(), and only then does Playwright wait for it. That is why declaring locators in the constructor is safe.

The button was renamed, the submit line in LoginPage was fixed, yet five tests still fail. What is the likeliest cause and what to do?

Answer

Those five tests do not use the Page Object and have their own getByRole('button', { name: 'Sign in' }). The class protects only those who use it. Find them by searching for the button name and move them to LoginPage, and in code review do not let direct login locators through.

In an interview. Junior: A Page Object gathers a page's locators and actions in one class, so when the markup changes I edit one place and the test reads as a scenario: loginPage.login(user) instead of three clicks. Middle/Senior: It separates reasons for change: a scenario changes with behaviour, locators with markup. In Playwright locators are lazy, so creating them in the constructor is safe. I set a class's boundary by the meaning of the screen, not the URL, and extract repeated parts into components. For a small suite a helper function is enough, and Page Object pays off when there are many tests and the markup changes.

A minimal Page Object in Playwright

A minimal Page Object has three duties: take page, declare locators and describe actions. Page comes through the constructor, locators are readonly fields, actions are async methods named by intent. Locators stay public so that the test writes web-first assertions with expect(locator), and the assertions themselves stay in the test. A locator is lazy and does not hold a DOM node, so creating it in the constructor costs nothing.

Patterns · Page Object

A Page Object of 15 lines or 150: what must it have from day one?

A team decided to write a Page Object for login. One developer builds a class with a few public locators and a login() method, another a dozen methods such as clickSubmitButton and typeEmail. Both are "right", but the test from the first reads as a scenario and from the second as a record of clicks, and you cannot write assertions in it without hacks. This lesson shows a minimal Page Object where every part has a reason, and what all good versions share.

How it works and why. The class has three duties. First: receive page from outside through the constructor. Then it works with the page the test gave it, not with a global variable, and does not disturb parallel tests, because each test gets its own page. Second: declare locators as readonly fields. That is the "map" of the screen, and in Playwright it is cheap because a locator is lazy. Third: describe actions as methods with business names that return a Promise, because every action is asynchronous.

When a Page Object searches for anything

new LoginPage(page)locators created, the DOM is untouchedawait loginPage.goto()page open, still no searchawait loginPage.login(…)each fill and click searches and waitsawait expect(loginPage.alert)searches again, retries until the timeout
Figure 1. Creating the class searches for nothing. Every action and every assertion resolves the locator anew, so the class does not “rot” when the page re-renders.

The last property matters: a locator does not hold a reference to a concrete DOM node. If the app repainted the button, the next action finds the new one. That is why a Page Object stores locators, not search results (ElementHandle), which can go stale.

Example: LoginPage and a test. Below is the class with the four important places marked.

import { type Locator, type Page } from '@playwright/test';

export class LoginPage {
1  readonly email: Locator;
  readonly password: Locator;
  readonly submit: Locator;
  readonly alert: Locator;

2  constructor(private readonly page: Page) {
    this.email = page.getByLabel('Email', { exact: true });
3    this.password = page.getByLabel('Password', { exact: true });
    this.submit = page.getByRole('button', { name: 'Log in' });
    this.alert = page.getByRole('alert');
  }

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

4  async login(email: string, password: string) {
    await this.email.fill(email);
    await this.password.fill(password);
    await this.submit.click();
  }
}
  1. Locators are public: the test itself calls expect(loginPage.alert) with auto-waiting.
  2. The page comes through the constructor, not from a global variable.
  3. The name “Password” without exact would also find “Confirm password” and fail with a strict mode violation.
  4. The method describes intent (“log in”), not mechanics (“click”).

The third of the four points concerns getByLabel: by default it matches a substring case-insensitively, so “Password” also finds “Confirm password”. When a locator matches several elements, an action throws a strict mode violation. { exact: true } requires a full match. The line goto('/login') is relative, so the config must have a baseURL.

Now how the class gets into a test. You can create it by hand in every test, but it is more convenient to hand that to a Playwright fixture: it builds the class with the right page and removes the boilerplate.

// fixtures.ts
import { test as base } from '@playwright/test';
import { LoginPage } from './login-page';

export const test = base.extend<{ loginPage: LoginPage }>({
  loginPage: async ({ page }, use) => {
    await use(new LoginPage(page));
  },
});
export { expect } from '@playwright/test';

// login.spec.ts
import { test, expect } from './fixtures';

test('wrong password shows an alert', async ({ loginPage }) => {
  await loginPage.goto();
  await loginPage.login('qa@test.com', 'wrong');
  // the check is in the test, not hidden in the Page Object
  await expect(loginPage.alert).toHaveText('Invalid credentials');
});

The test is short and reads as a scenario: open, sign in, check the message. The assertion stays in the test: it decides what counts as a correct result. How many fixtures and which scopes are covered in the lessons on fixtures; for a Page Object the typical fixture has test scope, because the page is new for every test.

A method name: intent or mechanics

Wrong

clickSubmitButton()

Named by mechanics. If the markup changes (the button becomes a link) the name lies. The test has ten click steps.

Right

login(email, password)

Named by intent. The clicks inside may change while the test and the name stay true.

Figure 2. A method name must survive a markup change.

Limits and alternatives. If an action leads to another page, the classic version has the method return a new Page Object (return new DashboardPage(this.page)). In Playwright it is optional: page is the same, so the test can create the needed class itself or get it from a fixture. Returning a new class is useful only when it removes a line from the test. Public locators slightly break "pure" encapsulation: the test sees how the page is built. It is a deliberate compromise for web-first assertions, because without access to the locator a test cannot write expect(locator) with auto-waiting. A version without public locators forces an expectError() method for every check and the class grows. Another alternative: a plain locator map object without methods, or helper functions. For complex multi-step scenarios one more layer appears, covered in the lesson on Facade.

Common mistakes.

  • isVisible() or getText() methods instead of returning a locator: the test gets a snapshot of state without waiting and becomes unstable.
  • A missing await before a Page Object method call: the test moves on without waiting for the action and the error shows up elsewhere.
  • The class calls page.goto in the constructor: a constructor cannot be async, so nobody awaits the call and the action is lost. Opening the page must be a separate async method.
  • Locators tied to position (nth, CSS chains): the class is built but stability is not. Prefer roles, labels and test ids.

Check yourself

The form has the fields “Password” and “Confirm password”. The class has this.password = page.getByLabel('Password'). What happens on fill() and how to fix it?

Answer

getByLabel by default matches a substring case-insensitively, so the locator matches two fields and fill() throws a strict mode violation. The fix: page.getByLabel('Password', { exact: true }) or getByRole('textbox', { name: 'Password', exact: true }).

A test calls await loginPage.login(...) and the next line is expect(loginPage.alert).toHaveText('Invalid credentials'). Why is no separate waitFor needed between them?

Answer

login() waits for click to finish, and expect(locator) is a web-first assertion: it repeats the search and the comparison until the expect timeout. The message may appear with a delay and the test tolerates it. An explicit waitForTimeout would only slow the test down.

In an interview. Junior: My Page Object receives page in the constructor, keeps locators as readonly fields and has async methods with business names. I leave the locators public so I can write checks with expect(locator) in the test. Middle/Senior: A locator is lazy and holds no DOM node, so the class does not depend on re-rendering and creating it in the constructor costs nothing. I hand the class to the test through a fixture and name methods by intent, not by clicks. Returning a new Page Object after navigation is optional in Playwright: I do it only when it removes code from the test.

Assertions in a Page Object, god objects and inheritance

A Page Object has one reason to change: the page changed, so business assertions with hard-coded values, god objects and deep inheritance hurt it. Assertions stay in the test, with a page-state wait such as expectLoaded allowed; shared parts move into components through composition and preconditions into fixtures. A method returning a boolean through isVisible gives a snapshot without waiting, so a locator is returned instead.

Patterns · Page Object

A Page Object has verifyTotalIs100() and the test does not show what it checks. Where is the line?

A Page Object started with two methods and a year later it is a file of 1500 lines. It has verifyTotalIs100(), three different ways to log out, a waitForTimeout after every click and a base class that three more inherit from. The test "add items and check the total" reads as five method calls, and what it actually checks is not visible. This lesson takes apart three typical failures: assertions inside, a god object and inheritance chains, shows the fix and names the trade-offs honestly.

How it works and why. A Page Object has one reason to change: the page changed. Every extra responsibility adds another reason. An assertion in the class means the class changes when the requirement for the result changes. Creating data means a change when the API changed. A base class with utilities for everyone means the class changes when anything in the project changes. All three failures share a root: the class stops describing a page and becomes a warehouse for everything. So the cure is not "prettier code" but a return to one responsibility.

Assertions. There are two positions. Fowler advises keeping checks in tests: the class shows how the page is built and the test decides what counts as correct. An acceptable compromise: a method that waits for the page's own state (expectLoaded() checks that the heading is visible), because that is synchronisation, not a business check. A method verifyTotalIs100() is worse: the number 100 is hidden from the test, the method works for one value only, and on failure the report shows a class, not a scenario.

Where the total check lives

Wrong

verifyTotalIs100() in the Page Object

The goal of the test is hidden and the number is baked into the method. A total of 250 needs another method.

Right

expect(orders.total) in the test

The number and the condition are visible in the scenario. The class gives only the total locator, one for all tests.

Figure 1. The class describes where the total is. The test says what it must be.

Inheritance. A chain BasePage → AuthenticatedPage → AdminPage → AdminUsersPage looks tidy until the base class has to change. Then everything below is affected, and to understand where a method comes from the reader walks through four files.

An inheritance chain

BasePagespinner, cookies, utilities↳ AuthenticatedPagesigned-in state, the user menu↳ AdminPageadministrator rights↳ AdminUsersPageyour method: in which of the four files?
Figure 2. Each level adds methods for all below it. A new page that needs only some of them still inherits all.

Example: from a god object to two classes. The initial class. Four problem places are marked.

export class OrdersPage {
  constructor(private page: Page) {}

1  async verifyTotalIs100() {
    await expect(this.page.locator('.total')).toHaveText('100');
  }
  async addItem(name: string) {
    await this.page.locator('.search').fill(name);
    await this.page.locator('.add-btn').click();
2    await this.page.waitForTimeout(2000);
  }
  async logout() {
3    await this.page.locator('.avatar').click();
    await this.page.locator('text=Logout').click();
  }
4  async isCartEmpty() {
    return this.page.locator('.cart-empty').isVisible();
  }
  // …40 more methods: filters, admin tables, checkout
}
  1. An assertion in the class: the number is baked into the name and the goal of the test is hidden.
  2. waitForTimeout(2000) instead of auto-waiting: slow, and still unstable on a slow machine.
  3. The user menu lives in OrdersPage. The same .avatar gets copied into every class and drifts apart.
  4. isVisible() does not wait: it answers at once, and a test that checks it with toBe(true) is unstable.

What such a failure looks like in the report

1Error: expect(locator).toHaveText(expected) failed

Locator:  locator('.total')
2Expected: "100"
Received: "90"
Timeout:  5000ms

3  at OrdersPage.verifyTotalIs100 (pages/orders-page.ts:5:47)
4  at tests/orders.spec.ts:9:16
  1. What: the total check failed. The error text itself is the same as for any assertion.
  2. How much: 100 was expected, 90 received. Why exactly 100 is not said in the report: the number is baked into the method.
  3. Where: the first frame leads into the Page Object file, not into the test.
  4. Scenario: only the second frame shows the test, but it does not say what the test was checking.

What to do

Keep the locator in the class and write the check in the test: expect(orders.total).toHaveText('100'). Then the first frame of the error points at a line of the scenario, and the number is right there.

Figure 3. The real error format (shortened): the numbers lead to the explanations.

The diagnosis from the symptoms: the class collects whatever the tests wanted, so it mixes the orders page, the header, synchronisation and checks. The cure has three steps: move the header into a component, remove the waits and the assertions, give the locators to the test.

export class Header {
  readonly menu: Locator;
  readonly logoutItem: Locator;

  constructor(page: Page) {
    this.menu = page.getByRole('button', { name: 'Account' });
    this.logoutItem = page.getByRole('menuitem', { name: 'Log out' });
  }

  async logout() {
    await this.menu.click();
    await this.logoutItem.click();
  }
}

The header is now one for the whole project, and every Page Object plugs it in by composition: this.header = new Header(page). Instead of a BasePage with everything, a class has only the parts it needs.

export class OrdersPage {
  readonly header: Header;
1  readonly total: Locator;
  readonly emptyCart: Locator;

  constructor(private readonly page: Page) {
2    this.header = new Header(page);
    this.total = page.getByTestId('order-total');
    this.emptyCart = page.getByText('Your cart is empty');
  }

3  async addItem(name: string) {
    await this.page.getByRole('searchbox').fill(name);
    await this.page.getByRole('button', { name: 'Add' }).click();
  }
}
  1. The locator is public: the test checks the total itself.
  2. The header is plugged in by composition, not inheritance.
  3. An action without sleep: Playwright waits for the search field and the button itself.

The test now shows everything important:

test('total after two items', async ({ page }) => {
  const orders = new OrdersPage(page);
  await page.goto('/orders');
  await orders.addItem('Keyboard');
  await orders.addItem('Mouse');
  await expect(orders.total).toHaveText('100');
  await expect(orders.emptyCart).toBeHidden();
  await orders.header.logout();
});

The number 100 and the conditions are visible in the scenario. Instead of isCartEmpty() with a boolean, the test uses expect(orders.emptyCart).toBeHidden(), which retries until the condition holds. If the same check repeats in dozens of tests, a method expectTotal(value) is acceptable too: the number comes from the test.

Limits and alternatives. None of the rules is absolute. Some teams deliberately put assertions in the Page Object, and for two or three repeated checks with parameters it works, especially when everyone understands the convention. The problem starts when names turn into verifyXIsY. A base class is sometimes justified too, if it is tiny: two or three things that every page really needs. But as soon as a second level appears, it is time to move to composition. For complex screens with repeated blocks there are components, for shared setup (login, data) Playwright fixtures, and for scenarios with different roles Screenplay, which swaps pages for tasks. Each option adds its own layer, so pick the one that solves a real problem of your suite.

Common mistakes.

  • Methods like verifyTotalIs100: the test does not show its goal and the class grows with every new value.
  • A class of a thousand lines "about everything": constant merge conflicts, duplicate methods, nobody knows what already exists. Split by screens and components.
  • waitForTimeout inside methods: it masks instability and slows everything. Rely on auto-waiting and web-first assertions.
  • A method that returns a boolean from isVisible(): that is a snapshot without waiting. Return the locator and check it through expect.
  • A Page Object creates data or calls the API: that is another responsibility. Preconditions belong to fixtures and App Actions.

Check yourself

A test has expect(await orders.isCartEmpty()).toBe(true) and sometimes fails on a slow environment. What happens and how to fix it?

Answer

isVisible() does not wait: it returns the state at the moment of the call, so while the cart is still emptying we get false and the test fails. The fix: return the locator and check it with a web-first assertion, await expect(orders.emptyCart).toBeVisible(), which retries the search until the timeout.

BasePage has waitForSpinner() that 30 pages inherit. A new page has no spinner. How to restructure without breaking the rest?

Answer

Move the spinner into a Spinner component (or a fixture) and plug it in by composition only for pages that need it. BasePage then loses the method and the new page does not inherit anything extra. This is “composition instead of inheritance”.

In an interview. Junior: I keep business checks in tests and leave only locators and actions in a Page Object. Very large classes I split into pages and components. Middle/Senior: A Page Object has one reason to change: the page changed. An assertion with a baked-in value, data creation and a deep inheritance hierarchy add reasons, so I cure them by returning to one responsibility: checks to the test, shared parts to components through composition, preconditions to fixtures. I allow a page-state wait such as expectLoaded, and parameterised checks when the team has agreed on it.