跳到主要内容

页面对象模型

介绍

可以通过构建大型测试套件来优化编写和维护的便捷性。页面对象模型就是一种构建测试套件的方法。

页面对象代表你的 Web 应用的一部分。例如,一个电商 Web 应用可能有一个首页、一个商品列表页和一个结算页。它们都可以用页面对象模型来表示。

页面对象通过创建适合你的应用的更高级别 API 来简化编写,并通过将元素选择器集中到一处并创建可重用代码来避免重复,从而简化维护

实现

我们将创建一个 PlaywrightDevPage 辅助类来封装对 playwright.dev 页面的常见操作。在内部,它将使用 page 对象。

playwright-dev-page.ts
import { expect, type Locator, type Page } from '@playwright/test';

export class PlaywrightDevPage {
readonly page: Page;
readonly getStartedLink: Locator;
readonly gettingStartedHeader: Locator;
readonly pomLink: Locator;
readonly tocList: Locator;

constructor(page: Page) {
this.page = page;
this.getStartedLink = page.locator('a', { hasText: 'Get started' });
this.gettingStartedHeader = page.locator('h1', { hasText: 'Installation' });
this.pomLink = page.locator('li', {
hasText: 'Guides',
}).locator('a', {
hasText: 'Page Object Model',
});
this.tocList = page.locator('article div.markdown ul > li > a');
}

async goto() {
await this.page.goto('https://playwright.net.cn');
}

async getStarted() {
await this.getStartedLink.first().click();
await expect(this.gettingStartedHeader).toBeVisible();
}

async pageObjectModel() {
await this.getStarted();
await this.pomLink.click();
}
}

现在我们可以在测试中使用 PlaywrightDevPage 类了。

example.spec.ts
import { test, expect } from '@playwright/test';
import { PlaywrightDevPage } from './playwright-dev-page';

test('getting started should contain table of contents', async ({ page }) => {
const playwrightDev = new PlaywrightDevPage(page);
await playwrightDev.goto();
await playwrightDev.getStarted();
await expect(playwrightDev.tocList).toHaveText([
`How to install Playwright`,
`What's Installed`,
`How to run the example test`,
`How to open the HTML test report`,
`Write tests using web first assertions, page fixtures and locators`,
`Run single test, multiple tests, headed mode`,
`Generate tests with Codegen`,
`See a trace of your tests`
]);
});

test('should show Page Object Model article', async ({ page }) => {
const playwrightDev = new PlaywrightDevPage(page);
await playwrightDev.goto();
await playwrightDev.pageObjectModel();
await expect(page.locator('article')).toContainText('Page Object Model is a common pattern');
});