1. 页面对象模型的构成
页面对象是将特定网页(或其部分)的所有交互和元素封装在一个类中的一种设计模式。这种分离方式带来了三个主要组成部分:
-
• 元素选择器:指向网页中特定元素的定义。
-
• 方法:封装与网页元素交互的一个或多个函数。
-
• 属性:与页面相关的附加信息或属性,例如其URL。 POM的核心在于抽象。您不仅是在编写测试,而是在为应用程序的用户界面创建一个直观的接口。
2. 理解页面对象模型的重要性
使用POM
确保了测试脚本创建的有序性。其核心思想是将UI交互和元素抽象为易于管理的对象。这种抽象使得UI
的变化只需在一个地方进行更新,从而使测试脚本对频繁的应用更新保持韧性。
例如,考虑登录到 https://ray.run/
的Web
应用。与其在每个测试中编写原始的Playwright
命令,不如将它们封装在 SignInPage
类中。
2.1 确定属性
以登录表单为例,首先确定页面的属性:
import { type Page } from '@playwright/test';
class SignInPage {
readonly page: Page;
readonly url: string = 'https://ray.run/signin';
public constructor(page: Page) {
this.page = page;
}
}
2.2 确定选择器
接下来,确定元素选择器:
import { type Page, type Locator } from '@playwright/test';
class SignInPage {
readonly page: Page;
readonly url: string = 'https://ray.run/signin';
readonly emailInputLocator: Locator;
readonly passwordInputLocator: Locator;
readonly signinButtonLocator: Locator;
public constructor(page: Page) {
this.page = page;
this.emailInputLocator = page.getByLabel('Email');
this.passwordInputLocator = page.getByLabel('Password');
this.signInButtonLocator = page.getByRole('button', { name: 'Sign In' });
}
}
2.3 确定动作
接着,识别页面上的操作:
async visit() {
await this.page.goto(this.url);
}
async login(email: string, password: string) {
await this.emailInputLocator.fill(email);
await this.passwordInputLocator.fill(password);
await this.signInButtonLocator.click();
}
2.4 确定断言
最后,识别断言: