Page Object Model with Playwright: Tutorial
By Ganesh Hegde, Community Contributor - October 25, 2024
Many organizations are giving more importance to test automation with DevOps and CI/CD taking center stage in the modern software world. Another reason is hundred percent manual testing doesn’t work in modern Agile systems, so there should be automation.
Read More: Best Practices for Test Automation
Just like development architecture and design patterns, test automation also needs a proper strategy, architecture, and design patterns. Many will think a lot while choosing a test automation tool, but they just forget the second part, plan and design pattern. The design patterns make the framework robust and make automation framework maintenance easier.
There are many test automation design patterns such as Page Object Model, Singleton, Façade, etc. In this guide, we’ll cover the Page Object Model as it is widely used, and fits all types of test automation tools.
What is a Page Object Model?
Popularly known as POM, Page Object Model is a design pattern that creates a repository for storing all web elements. It is useful in reducing code duplication and improves test script maintenance.
In Page Object Model, consider each web page of an application as a separate class file. Each class file will contain only corresponding web page elements. Using these elements, testers can perform operations on the website under test.
What is Page Object Model in Playwright?
Page Object Model in Playwright is a design pattern used i to create a structured approach for managing interactions with web pages. POM in Playwright helps in organizing test code by separating the representation of the web pages from the test logic, making tests more maintainable and readable.
Advantages of Page Object Model in Playwright
- Easy Maintenance: In web automation, everything depends on the DOM tree and selectors. The page object model makes maintenance easier even if there is a change in the DOM tree and selectors we don’t have to modify everywhere.
- Increased Reusability: Using POM, we can reuse the code which is written for another test. Also, we can create custom helper methods to achieve this. Code Reusability reduces the code, thus saving time and effort.
- Readability: As the tests are independent, it increases the readability
- Reduced Code Duplication: Common page interactions are encapsulated within the page objects, allowing multiple tests to reuse the same methods and reducing redundancy.
- Better Test Management: Grouping related actions and elements within a page object leads to a more coherent and manageable test suite.
- Enhanced Debugging: POM offer clear traceability. So, when a test fails, it’s easier to identify the issue within the specific page object rather than sifting through multiple test scripts.
Disadvantages of Page Object Model in Playwright
- Initial Setup Time: Initial design and building framework take some time.
- Advanced Skillset: Good coding skills are required to set the POM framework
- Higher Risk: Elements are stored in a shared file, so even a tiny mistake in the page object file can lead to breaking the whole test suite.
- Increased Complexity: For simple applications or small test suites, the POM can introduce unnecessary complexity by requiring additional classes and methods.
- Tight Coupling of Interdependencies: If page objects are not well-designed, they can become tightly coupled, making it difficult to modify one without affecting others.
- Limited Flexibility: The rigid structured nature of POM can make it harder to adapt to new testing strategies or tools without significant rework.
Implementing Page Object Model in Playwright
Pre-Requisites:
- Install Visual Studio Code: Download and Install Visual Studio Code(VSCode).
- Install NodeJS: Download and Install Node JS
Steps to get started with Page Object Model in Playwright
Step 1: Create a fresh new directory (ex: PlaywrightDemo) in VSCode
Step 2: Open Directory in Visual Studio Code. From VS code
Click on File > Open Folder > Choose newly Created Folder (PlaywrightDemo)
Step 3: From the VS Code, Click on Terminal Menu > Click on New Terminal
Step 4: Enter the below command to start the Playwright installation
npm init playwright@latest
Note: The above command asks a set of questions. Please provide appropriate inputs. In this tutorial, we are using typescript language.
Once you run the above command, the below set of files and folders will be automatically created
- tests folder: This folder contains actual test scripts. By default, an example.spec.ts file will be created inside this folder.
- .gitignore: This file helps if you are using git repository
- package.json and package-lock.json: This file helps to track dependencies, create a shortcut for running tests, etc.
- playwright.config.ts: This is the global configuration file for the Playwright, which you can configure with available options.
Set up/Add additional folders for Playwright page object model
- pages folder: Since we are using Page Object Model (POM) pattern the pages folder contains all the relevant page objects
- utility folder: The common code/function, which can be used in different tests can be placed here. For example, generating a random number, getting a date and time, etc.
Step 5: Install Browsers
Install browsers using the command
npx playwright install
Once you complete the above steps, your Playwright Test Automation Project/ Framework should look like the below.
Let’s consider a simple scenario.
Navigate to the Browserstack home page.
Click on Products Menu
Verify All Submenus are Present
Step 6: Create a page object file inside the pages folder and name it home.page.ts
To achieve the above flow, we need a URL, menu element, etc.
//home.page.ts import { expect, Locator, Page } from '@playwright/test'; export class BrowserstackHomePage { readonly url ="https://www.browserstack.com/"; readonly page: Page; readonly browserstackLogo: Locator; readonly productsMenu: Locator; readonly productmenudropdown:Locator constructor(page: Page) { this.page = page; this.browserstackLogo = page.locator('#logo'); this.productsMenu = page.locator('#product-menu-toggle'); this.productmenudropdown = page.locator('#product-menu-dropdown >div > ul >li >a >div[class="dropdown-link-heading"]'); } async goto(){ await this.page.goto(this.url); } async clickOnProducts(){ await this.productsMenu.waitFor({state:"visible"}); await this.productsMenu.click(); } }
Step 7: Create a test using the above page object file.
Create a test file inside the tests folder and name it home.test.ts
To create a test, we need to import the page object file. Like below.
import { BrowserstackHomePage } from '../pages/home.page';
Once we import, we need to write the script and verify the submenus.
// home.test.ts import { test, expect } from '@playwright/test'; import { BrowserstackHomePage } from '../pages/home.page'; test('Browserstack homepage verification', async ({ page }) => { const homepage = new BrowserstackHomePage(page); await homepage.goto(); await homepage.clickOnProducts(); await expect(homepage.productmenudropdown).toContainText(["Live", "Automate", "Percy", "App Live", "App Automate"]) });
After the creation of the above test file, your project looks like below
Step 8: Execute your test.
Execute you are using the below command
npx playwright test
By default Playwright test runs in headless mode, to run in headed mode use -– headed flag.
npx playwright test -–headed
Now that you have the tutorial in place, know that Playwright is supported by Browserstack which provides thousands of real devices where we can verify applications on real devices. A few advantages of Playwright are:
- Easy Setup and Configuration
- Multi-Browser Support
- Multi-Language Support
- Parallel Browser Testingomes in handy when multiple web pages have to be tested simultaneously.
- Built-in Reporters:
- Typescript Support out of the box
- CI/CD Integration Support
- Debugging Tools Support
Using Browserstack Integration with Playwright we can integrate our Playwright tests and make automation testing easier through robust design patterns. Not only that, speed up your Playwright tests by 30x with parallel testing to expand your test and browser coverage without compromising on build times.