playwright - 如何在 Typescript 中使用 Playwright 和 Playwright/test 实现页面对象模型?
问题描述
我已经尝试过剧作家页面对象文档和一些关于这个主题的 youtube 视频。我还阅读了 GitHub 问题(github page object issue),但是当存在多个页面对象类时,实现页面对象模型仍然存在问题。我了解一个简单的类和测试文件,但是当我想在另一个页面类中实例化一个页面类或为此继承时,如果有人可以帮助我,那将不胜感激。我想在特定方法之外的另一个类中实例化一个页面类,以便可以在多个方法中使用该实例。我希望有一个 Playwright/Test with Typescript 的样板,它不仅仅做一个基本的类,一个测试运行器文件。任何帮助将不胜感激。
我的代码示例:
export class LoginPage{
page: Page
/**
*
*/
constructor(page: Page) {
this.page = page;
}
public readonly logInButton ='text=Log in';
public async clickLoginButton() {
await this.page.click(this.logInButton);
}
}
export class AnotherPage{
page: Page
/**
*
*/
constructor(page: Page) {
this.page = page;
}
login = new Login(this.page); // This does not work as Property 'page' is used before its initialization
public async anotherPageMethod(): Promise<void> {
const login = new Login(this.page); // This works but this limits the scope of login to only one method. And I have to repeat this if I have mutiple methods using login.
await login.clickLogin();
}
}
解决方案
您必须将所有页面对象初始化移动到constructor
.
在您的情况下,您将拥有类似的东西:
export class AnotherPage {
page: Page
// add loginPage property
loginPage: Login
constructor(page: Page) {
this.page = page;
// initialize login page object
this.loginPage = new Login(page)
}
public async anotherPageMethod(): Promise<void> {
// loginPage accessible here
await this.login.clickLogin();
}
public async oneMoreAnotherPageMethod(): Promise<void> {
// loginPage accessible here too
await this.login.clickLogin();
}
}
推荐阅读
- javascript - Laravel-Mix:在 Laravel-Mix 升级到 v6 后,Vue 在 app.js 和 bootstrap.js 中不可用
- string - 用字符串编号替换地图字符
- laravel - 未找到存储中的 Laravel 文件
- javascript - d3js 不显示 GeoJson 数据
- vb.net - 使用 TOR 检查 URL 是否是实时的
- react-native - algolia 即时搜索显示几个项目并使用分页
- mysql-workbench - MySQLWorkbench 在 macOS Big Sur 11.1 上意外退出
- postgresql - 从 Docker 容器将 Postgres 数据库转储为 XML 或 JSON 文件
- arduino - 如何使 LED 序列永远循环?
- ios - 如何在 SwiftUI 和 iOS 14 中向领先的 navigationBarItems 添加徽章?