Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

playwright

I have tried 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) but still having issues implementing the page object model when there is more than a single page object class. I understand a simple class and test file but if someone can please help me when I want to instantiate a page class in another page class or inherit for that matter, that will be greatly appreciated. I want to instantiate a page class in another class outside of a specific method so I can use that instance in multiple methods. I wish there was a boilerplate for Playwright/Test with Typescript that does more than just basic one class, one test runner file. Any help will be greatly appreciated.

My code example:

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();
    }
}
like image 432
Kumar Avatar asked Oct 19 '25 10:10

Kumar


1 Answers

You have to move all page objects initialization to the constructor.

In your case you will have something like that:

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

}
like image 144
Yevhen Laichenkov Avatar answered Oct 22 '25 05:10

Yevhen Laichenkov