页面对象实现自动化测试,playwright框架

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 确定断言

最后,识别断言:


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员的世界你不懂

你的鼓励将是我创造的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值