The Page Object Pattern is a design pattern commonly used in automated UI testing, particularly with tools like Selenium WebDriver, to enhance test maintainability and readability. It encapsulates the interactions with a web page or UI component into a single class, representing the page's elements and actions as properties and methods.
Page object model design principle:
1. Page Object:
A class that represents a single web page or a significant UI component (e.g., a form or modal). It contains:
- Web Elements: Locators (e.g., ID, XPath, CSS) for UI elements like buttons, input fields, etc.
- Methods: Actions that can be performed on the page, such as clicking a button, entering text, or navigating.
2. Separation of Concerns:
- Test scripts focus on test logic (what to test and assertions).
- Page objects handle UI interactions (how to interact with elements).
3. Abstraction:
Tests interact with the page through high-level methods (e.g., login(username, password)) rather than low-level WebDriver commands (e.g., findElement).
Benefits
- Maintainability: If a UI element changes (e.g., a button's ID), you update only the page object, not multiple test scripts.
- Readability: Tests are more expressive, focusing on user actions rather than DOM manipulation.
- Reusability: Page objects can be reused across multiple tests or suites.
- Reduced Duplication: Common actions are defined once in the page object.
Create Page Objects
For each webpage or component, create a corresponding page object class. Here’s an example structure:
import { test, expect } from '@playwright/test'; export class LoginPage { constructor(page) { this.page = page; this.username = page.locator("id=user-name"); this.password = page.locator("id=password"); this.loginBtn = page.locator("id=login-button"); } async goto() { await this.page.goto("https://www.saucedemo.com/v1/"); } async setUsername() { await this.username.fill("standard_user"); } async setPassword() { await this.password.fill("secret_sauce"); } async clickLoginBtn() { await this.loginBtn.click(); } };
In this example, LoginPage encapsulates all interactions related to the login functionality.
Write Tests Using Page Objects
Now that you have your page objects set up, you can write tests that utilize these objects:
import { test, expect } from '@playwright/test'; import { LoginPage } from './LoginPage.js'; test("check the login functionality in web page", async ({ page }) => { const loginPage = new LoginPage(page); await loginPage.goto(); await loginPage.setUsername(); await loginPage.setPassword(); await loginPage.clickLoginBtn(); await loginPage.waitForTimeout(5000); });
The Page Object Model is an effective design pattern for structuring your Playwright tests. By encapsulating web elements and their behaviors within dedicated classes, you enhance test maintainability and readability.
No comments:
Post a Comment