
Playwright + POM: A Complete Guide to Clean and Maintainable Tests

End-to-end (e2e) testing has become a critical part of modern web development. As applications grow more complex, test automation must evolve to stay reliable, readable, and easy to maintain. This is where Playwright and the Page Object Model (POM) come together as a powerful combination.
Playwright is a fast, modern automation framework built by Microsoft that supports multiple browsers and offers an excellent developer experience. The Page Object Model (POM), on the other hand, is a design pattern that helps organize test code in a clean and scalable manner.
In this blog, we are going to learn how to create a page object model (POM) design pattern or framework using Playwright. The POM is used in test automation. It helps QAs to organize automation tests or test code by separating page objects from the main test code.
In POM, we use a class to represent each web page, and the class contains the elements of the web page, like dropdowns, fields, buttons, and links, etc. It also has actions that are used to perform actions on the page elements, like entering data in a field, clicking on a button, etc.
So, in simple terms, in POM, a test interacts with the respective page class instead of using locators/selectors directly.
In POM, we create one class for one web page. The page class contains locators and actions, whereas the test class uses page methods to perform actions. The test class also contains assertions.
For example:
Without POM (Bad Practice)
- await page.fill('#username', 'Haris');
- await page.fill('#password', '1234');
- await page.click('#login-button');
With POM (Good Practice)
- await loginPage.login('Haris', '1234');
Project Setup
Let’s start with creating a new folder on your MAC/Windows machine and renaming it, e.g., playwright_API_testing. Open the folder in your IDE, e.g., VS Code. Now, go to the terminal and run the following command:
npm init -y
It creates a package.json file and also initializes a Node project in the folder.
Now, we need a playwright, and I want to install the latest. Run the following command:
- npm init playwright@latest
- During setup, it asks for
- The language JavaScript/TypeScript?
- Where do you want to put the tests?
- Add a GitHub action workflow?
- Install Playwright browsers?
After installation, you will see
- package.json file is created in the project folder
- package-lock.json file is created in the project folder
Creating a Test
Now, I am creating a login test. So, I have selected the tests folder. It has one sample test already created. I am adding a new file in the test folder, e.g., arbisoft_chat.spec.js. I am creating test code using codegen. You can also write code manually.
Codegen records over steps and converts them to code. Enter the command below in the terminal to open codegen.
npx playwright codegenand hit enter.
It opens the browser and the test generator in two separate windows.

The recording is on by default, and it will record everything that we do in the browser. I have entered a test URL, e.g., arbisoft.com. I am doing the following steps next.
- Click customize cookie
- Click save and continue
- Click to open “Arbisoft Assistant”
- And clicking “Show me past projects”

The recorder is still ON. Now, I am stopping the recorder and copying the code generated by codegen. Paste the code in your IDE.
Running the Generated Test
In your IDE, go to the terminal and type the following command
- npx playwright test tests/arbisoft_chat.spec.js --project=chromium --headed
- This runs the test on the Chromium browser only

Use Page Object Model (POM)
In the project folder, create a folder, e.g., page, and create a file, e.g., arbisoft_chat.js, within it.
I am creating a class for the chat_assistant, and have created variables for my steps.
- Click customize cookie
- Click save and continue
- Click to open “Arbisoft Assistant”
- And clicking “Show me past projects”
As we need the chat_assistant object, I am creating a constructor and passing chat_assistant into it. The constructor has:
- this.page = page
I have defined all locators using this.
I have created a method chat_assistant_Page to perform actions on these locators. You can create separate functions for them as well.
Now, I am importing the page class chat_assistant in my test file. I have used chat_assistant and chat_assistant_Page inside my test. Run the test again using the command below.
npx playwright test tests/arbisoft_chat.spec.js --project=chromium --headed



Best Practices for Playwright with Page Object Model
- Keep page logic inside page objects
- All page locators and actions should be inside a page class. In the example, the chat_assistant class handles cookies, opening the chat widget, and interacting with the page. This keeps test files simple and clean.
- Define all locators in one Place
- Locators are defined in the constructor of the page object. This makes updates easier when the UI changes, because you only need to update selectors in one file.
- Use Playwright recommended selectors
- Using selectors like getByRole and getByText makes tests more stable and closer to real user behavior. These selectors are easier to read and less likely to break.
- Hide complex steps in Methods
- Multiple UI actions are grouped into one method. This hides complexity and makes the test easy to understand. The test only calls one method instead of many UI steps.
- Keep Tests short and clear
- Tests should focus on what is being tested, not how it works. A good test creates a page object and calls its method. This improves readability and reduces duplication.
- Handle iFrames inside page objects
- Any iframe logic should stay inside the page object. This keeps test files clean and avoids repeated iframe handling code.
- Rely on Playwright auto-waiting
- Playwright automatically waits for elements to be ready. Avoid using fixed waits and let Playwright handle synchronization for faster and more reliable tests.
Assertions belong in the test file. A page object performs actions and returns values or locators, and the test decides what to check with expect(). A page object that asserts hides the expected result from anyone reading the test. Its methods also become hard to reuse in a test that expects a different outcome, such as an error message after a failed login.
How to Structure a Playwright POM Project as the Suite Grows
A Playwright POM project scales when each page or major shared component gets its own page object and tests reach those objects through one fixtures file. A new page in the application then means one new class, and the existing classes keep working unchanged. Two QA engineers can also work on the checkout page and the dashboard page without editing the same file, which keeps merge conflicts down.
Here is a layout that follows this rule for the chat assistant example:
playwright.config.js
pages/
BasePage.js
CookieBanner.js
ChatAssistantPage.js
fixtures/
pages.js
tests/
arbisoft_chat.spec.jsThe cookie banner appears on every page of the site, which is why it gets its own class that any page object can use. Copying its locators into each page class would bring back the duplication POM is meant to remove.
Keep a Base Page Class One Level Deep
A base page class holds the page reference and the actions every page shares, such as opening a URL. Page classes extend it once. Deeper chains (BasePage, then AuthenticatedPage, then SettingsPage) make it hard to see which class defines a locator when a test fails. Shared UI parts such as the cookie banner work better as component classes that a page object creates.
The locator names below are illustrative; take the real ones from your codegen recording.
// pages/BasePage.js
class BasePage {
constructor(page) {
this.page = page;
}
async open(url) {
await this.page.goto(url);
}
}
module.exports = { BasePage };
// pages/CookieBanner.js
class CookieBanner {
constructor(page) {
this.customizeButton = page.getByRole('button', { name: 'Customize' });
this.saveButton = page.getByRole('button', { name: 'Save and continue' });
}
async saveDefaults() {
await this.customizeButton.click();
await this.saveButton.click();
}
}
module.exports = { CookieBanner };
// pages/ChatAssistantPage.js
const { BasePage } = require('./BasePage');
const { CookieBanner } = require('./CookieBanner');
class ChatAssistantPage extends BasePage {
constructor(page) {
super(page);
this.cookieBanner = new CookieBanner(page);
this.assistantButton = page.getByRole('button', { name: 'Arbisoft Assistant' });
this.pastProjectsOption = page.getByText('Show me past projects');
this.projectsReply = page.getByText('past projects').last();
}
async showPastProjects() {
await this.cookieBanner.saveDefaults();
await this.assistantButton.click();
await this.pastProjectsOption.click();
}
}
module.exports = { ChatAssistantPage };Share Page Objects Through Playwright Fixtures
Playwright fixtures can create page objects for each test, which removes the new ChatAssistantPage(page) line from every test file.
// fixtures/pages.js
const base = require('@playwright/test');
const { ChatAssistantPage } = require('../pages/ChatAssistantPage');
exports.test = base.test.extend({
chatPage: async ({ page }, use) => {
await use(new ChatAssistantPage(page));
},
});
exports.expect = base.expect;
// tests/arbisoft_chat.spec.js
const { test, expect } = require('../fixtures/pages');
test('assistant lists past projects', async ({ chatPage }) => {
await chatPage.open('https://arbisoft.com');
await chatPage.showPastProjects();
await expect(chatPage.projectsReply).toBeVisible();
});The test asks for chatPage by name and contains only the flow and the assertion. Adding another page object to the suite means one new class and one new entry in the fixtures file.
Benefits of POM
- It makes your code clean
- It gives structure to your code
- It reduces duplicates in your code
- If UI has changed, it updates quickly, i.e. If a locator has changed, you will update it in one place.
When Is POM Worth It in Playwright?
POM pays off once locators start repeating across tests: the application has several pages, the UI changes often, the suite will be maintained for months, or more than one person writes tests. A single smoke test or a throwaway script gains little from a page class, and the recorded codegen spec is fine there. The signal to refactor is the second test that needs the same locators.
POM reduces maintenance without removing it. When a button's label changes, one page object needs the update. When a user flow changes, the page object's methods and the tests that call them both change.
Conclusion
The Page Object Model (POM) is very simple and an effective way to build automation tests that are easily scalable and maintainable. By splitting the original code into test code and page code, our tests become simpler, and they become easy to read and update. POM helps us to reduce duplication and scale test automation with confidence.
The codegen feature of Playwright works very well with POM. In short, introducing POM with Playwright is an effective way to build well-structured end-to-end (e2e) test automation frameworks.
Playwright is a modern automation framework, and when combined with the Page Object Model, it becomes a clean, scalable, and maintainable testing solution.
If your goal is to build a professional-grade test automation framework, Playwright + POM is a combination you can trust. Start simple, follow best practices, and refactor as your test suite grows.
...Loading Related Blogs









