Review a Page Object Model for Refactoring
Reviews a Page Object Model class and returns specific refactoring suggestions: locator priority (role > label > testid > CSS), action vs assertion separation, action granularity (one method per user intent), and constructor cleanliness: with diff-style proposed changes.
When to use it
- Auditing a legacy POM that's grown unwieldy.
- PR review of a new POM file.
- Splitting a POM that has become responsible for multiple pages.
- Teaching engineers POM design principles by showing concrete improvements.
The prompt
<role>You are an automation framework specialist. You know that POMs go wrong in predictable ways: locator bloat, action/assertion entanglement, action granularity drift. You name each issue and propose a concrete diff.</role> <context>POM principles:- **Locator priority**: `getByRole` > `getByLabel` > `getByTestId` > CSS. CSS is last-resort.- **Action methods**: one method per USER INTENT, not per click. (`signIn(email, password)` not `clickEmail() + fillEmail() + ... + clickSubmit()`)- **Assertion methods**: `assertX()` style; reusable from spec.- **Constructor**: locator initialization only; no fetches, no waits, no side effects.- **Class boundary**: one POM per logical page (or component). If a POM has > 25 locators or > 20 methods, it likely covers multiple pages. Common smells:- Methods that just wrap a single click (`async clickSubmit() { await this.submit.click(); }`: inline that)- Constructor with side effects (`await this.goto()` in constructor)- Locators reused across methods via duplicate `page.locator(...)` calls- Mixed responsibilities (one POM has both Login and Dashboard methods)</context> <task>For the POM class below:1. Review locator priority: flag CSS selectors that could be roles/labels.2. Review action methods: flag granularity issues (too fine, too coarse).3. Review assertion methods: flag missing `assert` prefix, mixed-in actions.4. Review constructor: flag side effects.5. Review class boundary: flag if the POM is responsible for too many pages.6. Output diff-style refactoring proposals.</task> <input>POM class code: {pom_code}Framework: {framework}</input> <constraints>- Locator priority rule strict: role > label > testid > CSS.- Action methods at the USER INTENT level (sign in, add to cart, apply discount), not at the keypress / click level.- Diff format MUST use: / + lines.- Don't propose splitting a POM unless it has clear multi-page responsibility.- Suggested method names should match the page's domain (not `doThing()`).</constraints> <output_format>Five sections:1. **Locator review**: table: Current locator | Issue | Suggested2. **Action method review**: table: Method | Granularity | Issue | Suggested3. **Assertion method review**: table: Method | Issue | Suggested4. **Constructor + class boundary**: bullets on issues5. **Refactor diff**: diff-style changes</output_format> <approach>Before writing, count locators and methods; flag if > 25 / > 20 (likely needs split).</approach>## RoleAutomation framework specialist. POMs go wrong predictably: locator bloat, action/assertion entanglement, granularity drift. ## ContextPrinciples:- Locator priority: getByRole > getByLabel > getByTestId > CSS (last resort).- Action methods: one per USER INTENT, not per click.- Assertion methods: assertX style.- Constructor: locator initialization only; no fetches / waits / side effects.- Class boundary: > 25 locators or > 20 methods → likely multiple pages. Smells:- Methods wrapping single click- Constructor side effects- Locators reused via duplicate `page.locator(...)` calls- Mixed responsibilities (Login + Dashboard methods) ## TaskFor POM:1. Locator priority review.2. Action method granularity.3. Assertion method check (assertX prefix, no mixed actions).4. Constructor side effects.5. Class boundary (multi-page?).6. Diff-style refactor proposals. ## Input- POM code: {pom_code}- Framework: {framework} ## Constraints- Locator priority strict.- Action = user intent level.- Diff uses: / +.- Split only on clear multi-page responsibility.- Method names domain-specific. ## Output format5 sections: Locator review | Action method review | Assertion method review | Constructor + boundary | Refactor diff. ## ApproachCount locators + methods first; > 25 / > 20 = split.Example
Input
POM class code:
```typescript
import { Page, expect } from '@playwright/test';
export class LoginPage {
constructor(public page: Page) {
this.page.goto('/login'); // side effect in constructor
}
async clickEmail() {
await this.page.locator('#email').click();
}
async fillEmail(value: string) {
await this.page.locator('#email').fill(value);
}
async clickPassword() {
await this.page.locator('#password').click();
}
async fillPassword(value: string) {
await this.page.locator('#password').fill(value);
}
async clickSubmit() {
await this.page.locator('button.btn-primary').click();
}
async assertOnLoginPage() {
await expect(this.page).toHaveURL(/\/login/);
}
async navigateToDashboard() {
await this.page.click('button.btn-primary');
await expect(this.page).toHaveURL(/\/dashboard/);
}
async getDashboardGreeting() {
return this.page.locator('h1').textContent();
}
}
```
Framework: PlaywrightOutput
## 1. Locator review
| Current locator | Issue | Suggested |
|-----------------|-------|-----------|
| `this.page.locator('#email')` (repeated 2 times) | CSS-based locator + duplication across methods | `this.email = page.getByLabel('Email')`: initialize once in constructor, use getByLabel |
| `this.page.locator('#password')` (repeated 2 times) | CSS-based locator + duplication | `this.password = page.getByLabel('Password')` |
| `this.page.locator('button.btn-primary')` (repeated 2 times in different methods) | CSS-based locator + duplication; "btn-primary" not stable | `this.submit = page.getByRole('button', { name: 'Sign in' })` |
| `this.page.locator('h1')` | CSS without role consideration | `this.heading = page.getByRole('heading', { level: 1 })`: a bare `getByRole('heading')` matches every heading and fails strict mode |
## 2. Action method review
| Method | Granularity | Issue | Suggested |
|--------|-------------|-------|-----------|
| `clickEmail()` | Per-click | Too granular: tests rarely click before filling | Remove; inline `email.fill()` is sufficient |
| `fillEmail(value)` | Per-action | Useful as building block but should be part of higher-intent method | Keep, OR combine with fillPassword + submit into single `signIn()` |
| `clickPassword()` | Per-click | Too granular | Remove |
| `fillPassword(value)` | Per-action | Same as fillEmail | Keep or combine |
| `clickSubmit()` | Per-click | Too granular | Remove; inline submit.click() in user-intent methods |
| `navigateToDashboard()` | User intent | Method name doesn't match content: it actually submits the form. Misleading. Also contains an assertion (URL check) inside an action method. | Rename to `signIn(email, password)`; move URL assertion to a separate `assertOnDashboard()` |
## 3. Assertion method review
| Method | Issue | Suggested |
|--------|-------|-----------|
| `assertOnLoginPage()` | Good: single concern, asserts page state | Keep |
| `navigateToDashboard()` (mixed concern) | Contains assertion (URL check) + action (click): violates separation | Split into `signIn(email, password)` (action only) + `assertOnDashboard()` (assertion only) |
| `getDashboardGreeting()` (does it belong here?) | This is reading state from the DASHBOARD page, not the LOGIN page. Mixed page responsibility. | Move to a `DashboardPage` class |
## 4. Constructor + class boundary
- **Constructor side effect**: `this.page.goto('/login')` happens in constructor. This makes the POM impossible to use for tests that arrive at /login through a different route (e.g., redirect from another page). Move to a separate `goto()` method.
- **Class boundary violation**: `navigateToDashboard()` and `getDashboardGreeting()` are about the Dashboard page, not the Login page. Split into LoginPage and DashboardPage.
- **Locator initialization**: Currently re-creates locators on every method call (`this.page.locator(...)` repeated). Initialize once in constructor.
## 5. Refactor diff
```diff
-import { Page, expect } from '@playwright/test';
+import { Page, Locator, expect } from '@playwright/test';
+
+export class DashboardPage {
+ readonly page: Page;
+ readonly greeting: Locator;
+
+ constructor(page: Page) {
+ this.page = page;
+ this.greeting = page.getByRole('heading', { level: 1 });
+ }
+
+ async assertOnDashboard(): Promise<void> {
+ await expect(this.page).toHaveURL(/\/dashboard/);
+ }
+
+ async getGreeting(): Promise<string | null> {
+ return this.greeting.textContent();
+ }
+}
export class LoginPage {
- constructor(public page: Page) {
- this.page.goto('/login'); // side effect in constructor
+ readonly page: Page;
+ readonly email: Locator;
+ readonly password: Locator;
+ readonly submit: Locator;
+
+ constructor(page: Page) {
+ this.page = page;
+ this.email = page.getByLabel('Email');
+ this.password = page.getByLabel('Password');
+ this.submit = page.getByRole('button', { name: 'Sign in' });
}
- async clickEmail() {
- await this.page.locator('#email').click();
- }
-
- async fillEmail(value: string) {
- await this.page.locator('#email').fill(value);
- }
-
- async clickPassword() {
- await this.page.locator('#password').click();
- }
-
- async fillPassword(value: string) {
- await this.page.locator('#password').fill(value);
- }
-
- async clickSubmit() {
- await this.page.locator('button.btn-primary').click();
+ async goto(): Promise<void> {
+ await this.page.goto('/login');
+ await expect(this.email).toBeVisible();
+ }
+
+ async signIn(email: string, password: string): Promise<void> {
+ await this.email.fill(email);
+ await this.password.fill(password);
+ await this.submit.click();
}
- async assertOnLoginPage() {
+ async assertOnLoginPage(): Promise<void> {
await expect(this.page).toHaveURL(/\/login/);
}
-
- async navigateToDashboard() {
- await this.page.click('button.btn-primary');
- await expect(this.page).toHaveURL(/\/dashboard/);
- }
-
- async getDashboardGreeting() {
- return this.page.locator('h1').textContent();
- }
}
```
Result: 2 classes (LoginPage + DashboardPage), 3 methods on LoginPage (goto, signIn, assertOnLoginPage), 2 methods on DashboardPage (assertOnDashboard, getGreeting). Locators initialized once. No side effects in constructors.Common pitfalls
- Model proposes a 'cleanup' that loses functionality: verify methods aren't called by existing specs.
- Class split happens too aggressively (every page method becomes its own class). Force the 25-locator / 20-method threshold.
- Renaming methods breaks calling code: generate a deprecation map (`oldName -> newName`).
- Locator initialization moved to constructor but DOM isn't ready at construction time. Use Playwright's lazy locators (they don't query until used).
Tips
- Run after every 5-10 spec files are added; POMs drift toward bloat.
- Pair with `generate-playwright-pom` for the inverse problem (generating new POMs cleanly).
- Bundle multiple POM refactors into ONE PR for the codebase; cleaner history than per-POM PRs.
- When splitting a POM, validate that the new responsibilities each have own integration tests.
FAQ
POM vs Screenplay pattern?
POM is page-centric; Screenplay is actor-centric (\"Alice can sign in\" -> Alice.attemptsTo(SignIn.with(creds))). Screenplay is more verbose; pays off in suites with thousands of tests and very different user roles. POM is simpler; right for most projects.
When do I split one POM into multiple?
When you find yourself adding methods that describe a different page's behavior, OR when the class exceeds 25 locators / 20 methods. Mixed responsibility is the trigger; size is the symptom.
POM inheritance vs composition?
Both have uses. Inheritance: when pages share core behaviors (header, footer). Composition: when pages share atomic widgets (search bar, datepicker). Prefer composition unless you have clear base-class semantics.
Should POMs return promises?
Yes: most POM methods are async (perform browser actions). `signIn` returns Promise<void>. Action methods might also return relevant data (e.g., `createOrder()` returns the order id): that pattern is fine and useful for tests.