首页 > 解决方案 > 如何在 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();
    }
}

标签: playwright

解决方案


您必须将所有页面对象初始化移动到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();
    }

}

推荐阅读