Generate a Playwright Page Object Model with AI
Give the model a page description plus a list of UI elements and it returns a complete Page Object Model in TypeScript using Playwright's auto-waiting locators (getByRole / getByTestId), typed action and assertion methods, and a page-level fixture.
When to use it
- Starting a new Playwright suite and need a consistent POM scaffold per page.
- Migrating from CSS/XPath selectors to role-based, accessible locators.
- Refactoring existing POMs that mix concerns (actions + assertions + setup).
- Onboarding new automation engineers who need a reference structure.
The prompt
<role>You are a senior test automation engineer specializing in Playwright with TypeScript. You write Page Object Models that prioritize accessibility-first locators, auto-waiting, and clear separation of actions vs. assertions.</role> <context>The team uses Playwright >= 1.55 with TypeScript strict mode. We organize POMs as classes with constructor-injected Page, readonly Locator fields assigned in the constructor, async action methods, and async assertion methods that throw on failure. We use `@playwright/test` fixtures to provide POMs to tests.</context> <task>Generate a complete Page Object Model for the page I describe below, including:1. A class named `<PageName>Page` with constructor accepting `page: Page`.2. Readonly Locator fields using `getByRole`, `getByLabel`, or `getByTestId` (in that priority order). Use CSS selectors only as a last resort. Password inputs have no ARIA role: locate them with `getByLabel`.3. Async action methods (one per user intent, not per click).4. Async assertion helper methods using `expect(...).toBeVisible()` etc., with descriptive failure messages.5. A `goto()` method that navigates to the URL path and waits for a key element to be visible.6. A fixture export at the bottom that extends `test` with the new POM and re-exports `expect`.</task> <input>Page name: {page_name}Page URL path: {url_path}Elements (label → role/testid):{element_list} User intents on this page:{intents}</input> <constraints>- TypeScript strict mode: no `any`, no implicit returns.- No `page.waitForTimeout` and no hard sleeps.- Use only the locators listed in the input; if an element has no usable role, label or testid, say so in Next steps instead of guessing a selector.- Assertion methods must be named `assert<X>()`, action methods named in verb form.- Do NOT add comments inside method bodies; the method name carries the intent.</constraints> <output_format>1. The complete TypeScript file as a single code block.2. After the code block, a short bullet list (3-5 items) of "Next steps" explaining what to wire next (e.g., import `test` from this file in specs, add missing data-testid attributes to the app).</output_format> <approach>Before writing the final code, settle the locator strategy, action grouping, and assertion API.</approach>## RoleSenior test automation engineer specializing in Playwright with TypeScript. ## ContextPlaywright >= 1.55, TypeScript strict mode. POMs are classes with constructor-injected `page`, readonly Locator fields, async actions, async assertions. `@playwright/test` fixtures expose POMs to tests. ## TaskGenerate a complete Page Object Model for the page described below:1. Class `<PageName>Page` with a `page: Page` constructor.2. Readonly Locator fields, one per listed element.3. One async action method per user intent (not per click).4. Async `assertX()` methods using `expect(...)` web-first assertions.5. A `goto()` method that navigates and waits for a key element.6. A fixture export that extends `test` with the POM and re-exports `expect`. ## Input- Page name: {page_name}- URL path: {url_path}- Elements: {element_list}- User intents: {intents} ## Constraints- TypeScript strict; no `any`, no implicit returns.- Locators in priority: `getByRole` > `getByLabel` > `getByTestId` > CSS (last resort). Password inputs have no role: use `getByLabel`.- Use only the locators listed in the input; flag missing ones in Next steps instead of guessing.- No `page.waitForTimeout`. No hard sleeps.- Actions are verb-named methods; assertions are `assertX()` methods.- No body comments: let method names speak. ## Output format1. One TypeScript code block with the entire file.2. After the code, 3-5 bullets of "Next steps" (importing the fixture in specs, missing data-testids, etc.). ## ApproachPlan locator strategy and action grouping before writing the file.Task: Generate a Playwright Page Object Model in TypeScript. Input:- page_name: {page_name}- url_path: {url_path}- elements (label → role / label / testid): {element_list}- intents: {intents} Required parts:1. class <PageName>Page with a constructor(page: Page)2. readonly Locator fields, one per element3. one async action method per intent (verb-named)4. async assertX() methods using expect(...) web-first assertions5. goto(): navigates to url_path and waits for a key element6. fixture export extending test with the POM, re-exporting expect Rules:- TypeScript strict. No "any".- Prefer getByRole > getByLabel > getByTestId > CSS. Password inputs have no role: use getByLabel.- Use only the listed locators; never guess selectors.- No waitForTimeout. No sleeps.- No inline body comments. Output format:1. One TypeScript code block with the whole file.2. "Next steps": 3-5 bullets (fixture usage in specs, missing data-testids).Example
Input
Page name: Login URL path: /login Elements: - Email input → role=textbox, name="Email" - Password input → label="Password" - Submit button → role=button, name="Sign in" - Forgot password link → role=link, name="Forgot password?" - Error banner → testid="login-error" User intents: - Log in with valid credentials - Log in with invalid credentials and verify error - Navigate to forgot-password flow
Output
```typescript
import { Page, Locator, expect, test as base } from "@playwright/test";
export class LoginPage {
readonly page: Page;
readonly email: Locator;
readonly password: Locator;
readonly submit: Locator;
readonly forgotPassword: Locator;
readonly errorBanner: Locator;
constructor(page: Page) {
this.page = page;
this.email = page.getByRole("textbox", { name: "Email" });
this.password = page.getByLabel("Password");
this.submit = page.getByRole("button", { name: "Sign in" });
this.forgotPassword = page.getByRole("link", { name: "Forgot password?" });
this.errorBanner = page.getByTestId("login-error");
}
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 openForgotPassword(): Promise<void> {
await this.forgotPassword.click();
}
async assertErrorVisible(message?: string): Promise<void> {
await expect(this.errorBanner).toBeVisible();
if (message) await expect(this.errorBanner).toContainText(message);
}
async assertLoggedOut(): Promise<void> {
await expect(this.submit).toBeVisible();
}
}
export const test = base.extend<{ login: LoginPage }>({
login: async ({ page }, use) => {
await use(new LoginPage(page));
},
});
export { expect } from "@playwright/test";
```
Next steps:
- Import `test` and `expect` from this file in spec files instead of `@playwright/test`.
- Confirm the `data-testid="login-error"` attribute exists in the production markup.
- Wire the page's success path (post-login redirect) into a separate `DashboardPage`.Common pitfalls
- Output may include hard waits if you forget to forbid `waitForTimeout` in the constraints block.
- If the page has dynamic role names (e.g., localized), `getByRole` with a `name` option will break: switch to `getByLabel` or testid.
- Without a strict mode reminder, the model may emit `any` for the page param.
- Models sometimes invent helper methods that don't match the listed intents: review the action surface before pasting.
- `<input type="password">` has no ARIA role, so `getByRole('textbox', { name: 'Password' })` never matches: list password fields by label.
Tips
- Paste real role/testid values from your app, not guesses: the model can't infer them.
- Include the exact Playwright version in `<context>` if you depend on features added recently (e.g., `toHaveScreenshot` updates).
- For multi-step flows, prefer one action method per intent (`signIn(email, password)`) over one per click: keeps tests readable.
- Re-run the prompt with `intents` only when the page UI evolves; the locators block usually stays stable.
FAQ
Why does the prompt forbid `page.waitForTimeout`?
Hard sleeps create flaky tests because they pass on slow machines and fail on fast ones. Playwright's auto-waiting locators wait until the action is actionable: explicit timeouts are almost never the right answer in 2026.
Should I keep assertions inside the POM or in the spec?
Both. Page-state assertions like `assertErrorVisible()` belong on the POM because they're tied to that page's contract. Business-rule assertions (e.g., 'user has 3 orders') belong in the spec.
Can I use this prompt for component tests instead of E2E?
Yes: pass the `Locator` returned by `mount()` into the constructor instead of `Page`, build locators from it, and drop `goto()`. The locator priority and structure stay the same.
Does this prompt work for JavaScript (not TypeScript)?
Strip the type annotations from the output. The structure is identical, but you lose the compile-time guardrail against `any` locators.