Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST TOOLS MATH

Playwright Page Object Model


Share

Playwright Page Object Model

The Page Object Model (POM) is a way to organize tests where each page of your app gets its own class.

The class knows how to find things on the page and how to use them.

The tests call the class, and do not deal with locators at all.

In this chapter you will write a page object for the Todo List practice page, and one for the Login page.


Why Use Page Objects?

Many tests use the same page in the same way.

Without page objects, every test repeats the same locators, like getByPlaceholder('What needs to be done?').

If the page changes, you have to fix every one of those tests.

With a page object, the locator is written once, in one place.

You fix it there, and every test that uses it works again.

The tests also get shorter, and read like steps a user would take:

Example

await todoPage.addTodo('Learn Playwright');
await todoPage.completeTodo('Learn Playwright');


Create a Page Object

Page objects are plain JavaScript classes.

A common place for them is a pages folder next to the tests folder:

my-project/
  pages/
    todo-page.js
    login-page.js
  tests/
    todo.spec.js
    login.spec.js
  playwright.config.js

Here is the page object for the Todo List.

The locators are created in the constructor, and each thing a user can do is a method:

Example

pages/todo-page.js

// @ts-check
import { expect } from '@playwright/test';

export class TodoPage {
  /**
   * @param {import('@playwright/test').Page} page
   */
  constructor(page) {
    this.page = page;
    this.newTodo = page.getByPlaceholder('What needs to be done?');
    this.addButton = page.getByRole('button', { name: 'Add' });
    this.items = page.getByRole('listitem');
    this.count = page.getByTestId('todo-count');
  }

  async goto() {
    await this.page.goto('todo.html');
  }

  async addTodo(text) {
    await this.newTodo.fill(text);
    await this.addButton.click();
  }

  async completeTodo(text) {
    await this.page.getByRole('checkbox', { name: 'Complete ' + text }).check();
  }

  async deleteTodo(text) {
    await this.page.getByRole('button', { name: 'Delete ' + text }).click();
  }

  async showOnly(filter) {
    await this.page.getByRole('button', { name: filter, exact: true }).click();
  }

  async expectCount(text) {
    await expect(this.count).toHaveText(text);
  }
}

Example Explained

  • The constructor gets the Playwright page and keeps it in this.page
  • The locators are stored as properties, so tests can also use them, for example todoPage.items
  • Creating a locator does not touch the page, so it is safe to create them all in the constructor
  • goto() uses a relative URL, because the project config sets baseURL (see Config File)
  • addTodo(), completeTodo(), deleteTodo() and showOnly() are the actions a user can take
  • expectCount() is a helper for a check that many tests need
  • The @param comment tells your editor that page is a Playwright Page, so you get autocomplete

Use the Page Object in Tests

Import the class, create it with the test's page, and call its methods:

Example

tests/todo.spec.js

// @ts-check
import { test, expect } from '@playwright/test';
import { TodoPage } from '../pages/todo-page';

test('can add todos', async ({ page }) => {
  const todoPage = new TodoPage(page);
  await todoPage.goto();
  await todoPage.addTodo('Learn Playwright');
  await todoPage.addTodo('Write tests');
  await expect(todoPage.items).toHaveCount(2);
  await todoPage.expectCount('2 items left');
});

test('can complete a todo', async ({ page }) => {
  const todoPage = new TodoPage(page);
  await todoPage.goto();
  await todoPage.addTodo('Learn Playwright');
  await todoPage.addTodo('Write tests');
  await todoPage.completeTodo('Learn Playwright');
  await todoPage.showOnly('Done');
  await expect(todoPage.items).toContainText(['Learn Playwright']);
  await todoPage.expectCount('1 item left');
});

test('can delete a todo', async ({ page }) => {
  const todoPage = new TodoPage(page);
  await todoPage.goto();
  await todoPage.addTodo('Learn Playwright');
  await todoPage.deleteTodo('Learn Playwright');
  await expect(todoPage.items).toHaveCount(0);
});

The tests contain no locators.

They describe what the user does, and the page object knows how to do it.


A Login Page Object

Each page of your app gets its own class.

Here is one for the Login practice page:

Example

pages/login-page.js

// @ts-check
export class LoginPage {
  /**
   * @param {import('@playwright/test').Page} page
   */
  constructor(page) {
    this.page = page;
    this.username = page.getByLabel('Username');
    this.password = page.getByLabel('Password');
    this.loginButton = page.getByRole('button', { name: 'Log in' });
    this.error = page.getByRole('alert');
    this.welcome = page.getByTestId('welcome');
  }

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

  async login(username, password) {
    await this.username.fill(username);
    await this.password.fill(password);
    await this.loginButton.click();
  }
}

The same login() method works for a good and a bad password.

The tests decide what to expect:

Example

tests/login.spec.js

// @ts-check
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/login-page';

test('login works', async ({ page }) => {
  const loginPage = new LoginPage(page);
  await loginPage.goto();
  await loginPage.login('student', 'w3schools');
  await expect(loginPage.welcome).toHaveText('Welcome, student!');
});

test('wrong password shows an error', async ({ page }) => {
  const loginPage = new LoginPage(page);
  await loginPage.goto();
  await loginPage.login('student', 'wrong');
  await expect(loginPage.error).toHaveText('Wrong username or password.');
});

Run all the tests:

Example

npx playwright test

Output:

Running 5 tests using 5 workers

[1/5] [chromium] › tests/login.spec.js:12:1 › wrong password shows an error
[2/5] [chromium] › tests/todo.spec.js:25:1 › can delete a todo
[3/5] [chromium] › tests/todo.spec.js:14:1 › can complete a todo
[4/5] [chromium] › tests/login.spec.js:5:1 › login works
[5/5] [chromium] › tests/todo.spec.js:5:1 › can add todos
  5 passed (3.6s)

Keep Page Objects Small

A page object is a small helper.

These simple rules keep it useful:

  • One class per page, or per large part of a page (like a menu that is on every page)
  • Methods are actions a user can take: addTodo(), login()
  • Most checks stay in the test, so you can see what each test expects
  • Add a method when two or more tests need it, not before
  • Keep using Playwright locators inside the class, so you still get auto-waiting

Tip: Above, every test repeats new TodoPage(page) and goto().

In the next chapter, Fixtures, you will let Playwright create the page object for you.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.