在 Playwright 中重新创建页面对象?

问题描述 投票:0回答:2

在 Playwright(与许多其他自动化框架一样)中,您可以创建页面对象。使用 Playwrights 文档中的示例:https://playwright.dev/docs/test-fixtures#without-fixtures

你有一个看起来像这样的 .spec 文件(实际的页面对象类本身可以在上面看到,因为它很长而不发布它):

const { test } = require('@playwright/test');
const { TodoPage } = require('./todo-page');

test.describe('todo tests', () => {
  let todoPage;

  test.beforeEach(async ({ page }) => {
    todoPage = new TodoPage(page);
    await todoPage.goto();
    await todoPage.addToDo('item1');
    await todoPage.addToDo('item2');
  });

  test.afterEach(async () => {
    await todoPage.removeAll();
  });

  test('should add an item', async () => {
    await todoPage.addToDo('my item');
    // ...
  });

  test('should remove an item', async () => {
    await todoPage.remove('item1');
    // ...
  });
});

但是我想知道在这种情况下是否真的需要在每次测试之前重新创建页面对象?创建页面对象一次还不够好吗? (因为我们可以访问所有方法/等等......并且这些方法在测试之间不应该改变?

是否有理由为每个测试重新创建页面对象?

playwright pageobjects
2个回答
2
投票

使用

beforeAll
实例化 page 对象,以便文件中的所有测试都可以共享
page
对象,因为 todoPage 是在任何测试之外声明的套件级别变量。

test.beforeAll(async ({ page }) => {
    todoPage = new TodoPage(page);
  });

Playwright 文档建议像之前一样使用Each 来促进测试隔离,以便测试可以并行运行,因为它们应该绝对独立。


1
投票

我们可以创建静态页面对象,例如:

class StaticPageObject() {
  // no constructor

  static clickSomeBtn(page) {
   // now page should be feed to the PO methods
   page.locator("some-static-selector").click()
  }
}

这样我们就可以使用 PageObject 方法,例如:

StaticPageObject.clickSomeBtn(page) // no initialization required

如果

page
成为全球性的(这不是一个好方法),那么,

class StaticPageObject() {
  // no constructor

  static clickSomeBtn() {
   // now page should be feed to the PO methods
   global.page.locator("some-static-selector").click()
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.