菜单
开源

页面对象模型

处理大型测试套件时,一种流行的设计模式是页面对象模型,它可以提高代码的可维护性和可读性。

页面对象通常表示一个 HTML 页面或页面中的重要元素/组件,例如页眉或页脚。它是一种封装形式,将 UI 结构的细节隐藏起来,使其不暴露给其他地方,例如您的测试文件。通过页面对象模型,您需要在特定页面或页面内元素上进行的任何更改都集中在一个地方,从而易于维护并避免代码重复。

由于 k6 browser 旨在提供与 Playwright API 的大致兼容性,您可以利用任何现有的页面对象,并轻松地在 k6 browser 测试中重复使用它们。

实现

我们以一个在首页添加了预订表单的网站为例。假设您想编写一个测试来检查用户是否可以成功填写预订表单。

为了为首页建模页面对象,我们创建了一个名为 homepage.js 的页面对象类。在构造函数内部创建了不同的定位器,以便当 homepage 类被实例化时,页面定位器元素就可以使用了。

homepage.js 类还包含不同的方法,用于

  • 导航到首页
  • 提交表单
  • 获取验证消息

当需要更新定位器或对首页进行其他特定更改时,您只需更新 homepage.js 类。

JavaScript
import { bookingData } from '../data/booking-data.js';

export class Homepage {
  constructor(page) {
    this.page = page;
    this.nameField = page.locator('[data-testid="ContactName"]');
    this.emailField = page.locator('[data-testid="ContactEmail"]');
    this.phoneField = page.locator('[data-testid="ContactPhone"]');
    this.subjectField = page.locator('[data-testid="ContactSubject"]');
    this.descField = page.locator('[data-testid="ContactDescription"]');
    this.submitButton = page.locator('#submitContact');
    this.verificationMessage = page.locator('.row.contact h2');
  }

  async goto() {
    await this.page.goto('https://myexamplewebsite/');
  }

  async submitForm() {
    const { name, email, phone, subject, description } = bookingData;

    this.nameField.type(name);
    this.emailField.type(email);
    this.phoneField.type(phone);
    this.subjectField.type(subject);
    this.descField.type(description);
    await this.submitButton.click();
  }

  async getVerificationMessage() {
    return this.verificationMessage.innerText();
  }
}

您可以在测试类中导入 Homepage 类并调用所需的方法。这使得代码更容易理解,并强制区分测试逻辑和业务逻辑。

JavaScript
import { browser } from 'k6/browser';
import { expect } from 'https://jslib.k6.io/k6chaijs/4.3.4.0/index.js';

import { Homepage } from '../pages/homepage.js';
import { bookingData } from '../data/booking-data.js';

export default async function () {
  const page = await browser.newPage();

  const { name } = bookingData;

  const homepage = new Homepage(page);
  await homepage.goto();
  await homepage.submitForm();

  expect(await homepage.getVerificationMessage()).to.contain(name);

  await page.close();
}