In this article, we will learn about the page object model and how it is implemented in Playwright.
What's Page Object Model/POM?
- Also commonly known as POM, it is a design pattern that stores web elements as a repository in a separate class file.
- Each class file contains separate web page elements. In short terms, web pages are separated into each class file as shards and automated.
Pros:
- Easy to maintain as each class file have different locators for different pages.
- It can be used again for another test with a custom helper method, so this has increased reusability.
- As all tests are separated into shards, readability is good.
Cons:
- It takes time to build the framework initially.
- A good understanding of code is required for POM.
- A tiny miscalculation can destroy the whole test suite, as the elements are stored in a shared file.
POM In Action:
Let us create a separate class file for a login page from programsbuzz.
1.) Setup
- Create a folder with any name at the project level.
- Create a .js file named LoginPage for easy understanding.

2.) Class File Setup
class LoginPage {
constructor(page){
this.page = page;
this.userName = page.locator("#edit-name");
this.passWord = page.locator("#edit-pass");
this.clickLogin = page.locator('//form[@id="user-login-form"]//input[@id="edit-submit"]');
}
async goTo(){
await this.page.goto("https://www.programsbuzz.com/user/login");
}
async login(username,pass){
await this.userName.type(username);
await this.passWord.type(pass);
await this.clickLogin.click();
}
}
module.exports = {LoginPage};
- Create a class with the same name as the file name.
- Create a constructor within it.
- When a constructor is created, and a variable is created within it attached to 'this,' it is called a class variable so that it can be accessible.
- Inside the constructor, pass in the locators of our login page's username field, password field, and a login button.
- Also, let it know that this.page is equal to the page, which means that it is the page we will traverse.
- Methods for visiting the URL and login are created for adding actions.
- Finally, create an export module to let the project know that this class can be imported anywhere.
3.) Test
const {test, expect} = require('@playwright/test');
const{LoginPage} = require('../Pages/LoginPage');
test('ElementHandle', async ({page})=>
{
const name = "Naruto";
const loginPassword = "SHazam";
const lp = new LoginPage(page);
await lp.goTo();
await lp.login(name, loginPassword);
});
- Now that the class file is created, import the class file LoginPage in our test.
- Create an object for the class before beginning.
- Now, all methods from a class file can be accessed using lp.
- Remember to use await before the object.
Conclusion:
This is what it takes to create a simple POM structure in Playwright using Javascript.
Wed, 12/07/2022 - 11:15
Comments