App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide Page Object Model with Playwright: Tutorial

Page Object Model with Playwright: Tutorial

By Ganesh Hegde, Community Contributor -

Table of Contents

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.

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.

Advantages of Page Object Model

  1. 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. 
  2. 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.
  3. Readability: As the tests are independent, it increases the readability

Disadvantages of Page Object Model

  1. Initial design and building framework take some time.
  2. Good coding skills are required to set the POM framework
  3. 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.

What is Playwright?

Playwright is an open-source Test Automation Tool, Initially developed by Microsoft contributors. Playwright supports programming languages such as Java, Python, C#, and NodeJS. Playwright Comes with Apache 2.0 License and is most popular with NodeJS with Javascript/Typescript.

Implementing Page Object Model in Playwright

Pre-Requisites:

  1. Install Visual Studio Code: Download and Install Visual Studio Code(VSCode).
  2. 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.

Screenshot 2022 05 25 at 6.47.41 PM

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

Screenshot 2022 05 25 at 6.54.50 PM

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

Screenshot 2022 05 25 at 6.58.38 PM

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.

Run Playwright Tests On BrowserStack

Tags
Automation Frameworks Automation Testing

Featured Articles

Page Object Model and Page Factory in Selenium

How to Perform Visual Regression Testing Using Playwright

How to start with Playwright Debugging