如何使用 Playwright 和 Playwright/test 在 Typescript 中实现页面对象模型?

How to implement Page Object Model with Playwright and Playwright/test in Typescript?

我已尝试 playwright page object doc and a couple of youtube videos on this subject matter. I have also read the GitHub issues (github page object issue) 但当有多个页面对象 class 时,在实现页面对象模型时仍然存在问题。我理解一个简单的 class 和测试文件,但是如果有人可以帮助我,当我想在另一个页面 class 中实例化页面 class 或为此继承时,将不胜感激.我想在特定方法之外的另一个 class 中实例化一个页面 class,这样我就可以在多个方法中使用该实例。我希望 Playwright/Test 有一个带有 Typescript 的样板文件,它不仅仅是基本的 class,一个测试运行文件。任何帮助将不胜感激。

我的代码示例:

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();
    }

}