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

Patterns › Page Object Model

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.

More articles in this chapter