Skip to content

Instantly share code, notes, and snippets.

@graffhyrum
Created September 20, 2023 23:43
Show Gist options
  • Select an option

  • Save graffhyrum/f0f4469fdd014bc3bf1d44f2a767aa2a to your computer and use it in GitHub Desktop.

Select an option

Save graffhyrum/f0f4469fdd014bc3bf1d44f2a767aa2a to your computer and use it in GitHub Desktop.
Class-based POM vs factory function POM
import {expect, Locator, Page} from '@playwright/test';
// Page Object Model
export class PlaywrightDevPage {
readonly page: Page;
readonly getStartedLink: Locator;
readonly gettingStartedHeader: Locator;
readonly pomLink: Locator;
readonly tocList: Locator;
constructor(page: Page) {
this.page = page;
this.getStartedLink = page.locator('a', {hasText: 'Get started'});
this.gettingStartedHeader = page.locator('h1', {hasText: 'Installation'});
this.pomLink = page
.locator('li', {
hasText: 'Guides',
})
.locator('a', {
hasText: 'Page Object Model',
});
this.tocList = page.locator('article div.markdown ul > li > a');
}
async goto() {
await this.page.goto('https://playwright.dev');
}
async getStarted() {
await this.getStartedLink.first().click();
await expect(this.gettingStartedHeader).toBeVisible();
}
async pageObjectModel() {
await this.getStarted();
await this.pomLink.click();
}
}
// Factory pattern
const PlaywrightDevPage2 = (page: Page) => {
const getStartedLink = page.locator('a', {hasText: 'Get started'});
const gettingStartedHeader = page.locator('h1', {hasText: 'Installation'});
const pomLink = page
.locator('li', {
hasText: 'Guides',
})
.locator('a', {
hasText: 'Page Object Model',
});
const tocList = page.locator('article div.markdown ul > li > a');
const goto = async () => {
return await page.goto('https://playwright.dev');
};
const getStarted = async () => {
await getStartedLink.first().click();
return await expect(gettingStartedHeader).toBeVisible();
};
const pageObjectModel = async () => {
await getStarted();
return await pomLink.click();
};
return {
goto,
getStarted,
pageObjectModel,
};
};
// Usage examples
const aClassPom = new PlaywrightDevPage(page);
await aClassPom.goto();
const aFactoryPom = PlaywrightDevPage2(page);
await aFactoryPom.goto();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment