Class-based vs factory function for Page Object Models in Playwright - which do you use?
I recently joined a new repo and noticed the codebase has two different styles of Page Object Model patterns and I was wondering if there's a preference. From the docs I only see references to the class-based pattern.
Class-based:
class AddTodoPage {
public readonly page: Page;
public readonly titleInput: Locator;
public readonly submitButton: Locator;
constructor(page: Page) {
this.page = page;
this.titleInput = page.getByRole('textbox', { name:
'Title' });
this.submitButton = page.getByRole('button', {
name: 'Add Todo' });
}
async goto() {
await this.page.goto('/todos/new');
}
async fillTitle(title: string) {
await this.titleInput.fill(title);
}
async submit() {
await this.submitButton.click();
}
}
// Usage
test('Adds a todo', async ({ page }) => {
const addTodoPage = new AddTodoPage(page);
await addTodoPage.goto();
await addTodoPage.fillTitle('Buy milk');
await addTodoPage.submit();
});
Factory function:
function createAddTodoPage(page: Page) {
return {
goto: () => page.goto('/todos/new'),
fillTitle: (title: string) =>
page.getByRole('textbox', { name: 'Title'
}).fill(title),
submit: () => page.getByRole('button', { name: 'Add
Todo' }).click(),
};
}
// Usage
test('Adds a todo', async ({ page }) => {
const addTodoPage = createAddTodoPage(page);
await addTodoPage.goto();
await addTodoPage.fillTitle('Buy milk');
await addTodoPage.submit();
});