My current implementation uses a Page Object Model to handle browser specification. However, I encountered an issue where assigning a new context from the browser and then assigning it to the page does not work as expected due to the asynchronous nature of the method. This makes it impossible to create the object without initializing it with a method after its creation.
I am wondering if it is possible to assign an async value in the constructor or if there is a better pattern to follow?
export class AppPage {
readonly browser: Browser;
readonly page: Page;
readonly context: BrowserContext;
public currentPage: Page;
constructor(browser: Browser) {
this.browser = browser;
// It is not feasible to assign in the constructor as these are async methods
// this.context = await this.browser.newContext();
// this.page = await context.newPage();
}
async initialize() {
const context = await this.browser.newContext();
const page = await context.newPage();
// An extra method call is required for initialization
this.currentPage = page;
}
async goto() {
await this.currentPage.goto('https://playwright.dev');
}
}
The current implementation requires initializing the page assignment.
test('test using context with page object model', async ({ browser }) => {
const app = new AppPage(browser);
await app.initialize();
await app.goto();
});