This prompt is designed for SDETs and automation engineers who need to scaffold maintainable Page Object Model (POM) classes from UI descriptions, wireframes, or existing procedural test scripts. Use it when you have a defined page or component with known interactions and want to produce a POM class with encapsulated selectors, action methods, and assertion helpers before writing automation code. The ideal input is a structured description of the page's purpose, key elements (with their semantic meaning, not just raw selectors), and the primary user workflows that traverse this page. This prompt is most effective early in the automation development cycle, acting as a design tool that enforces consistency and reduces the accumulation of brittle, copy-pasted locators across a test suite.
Prompt
Page Object Model Generation Prompt for Test Cases

When to Use This Prompt
Understand the ideal conditions, required inputs, and limitations for using the Page Object Model generation prompt.
The prompt assumes you can describe the page structure, key elements, and user workflows in natural language. It is not a replacement for framework-specific runtime behavior tuning, nor does it handle dynamic element resolution strategies that require live DOM inspection. Do not use this prompt to generate code for a page you haven't designed or explored; the output quality is directly proportional to the clarity of your input description. For example, a good input specifies 'a login form with a username text field, a password field with a show/hide toggle, a 'Sign In' button, and a 'Forgot Password' link,' rather than just 'a login page.' The prompt will then generate a class with methods like login(username, password), togglePasswordVisibility(), and clickForgotPassword(), each encapsulating its own selectors. The generated code should be treated as a first draft that requires human review for selector strategy, framework-specific conventions, and cross-page coupling risks before being committed to a repository.
After generating the POM scaffold, your next step is to review the output against your team's specific coding standards and the real, rendered DOM. Pay close attention to the 'Review Criteria' section of the output, which flags potential issues like methods that assume a single responsibility but have side effects, or selectors that are overly generic. Avoid using the generated class directly in a critical path without first validating its selectors against your actual application under test and integrating it with a concrete test to ensure the action methods and assertion helpers behave as expected in a live browser context.
Use Case Fit
Where the Page Object Model generation prompt delivers value and where it falls short. Use these cards to decide if this prompt fits your current automation context.
Good Fit: Scaffolding from UI Specs
Use when: You have a UI description, component library docs, or a design system reference and need a first draft of a POM class. Guardrail: Always review generated selectors against the live DOM; design docs often miss dynamic attributes or framework-generated IDs.
Good Fit: Refactoring Scripts into POM
Use when: You have existing Playwright or Selenium scripts with inline selectors and want to extract them into page objects. Guardrail: The prompt can identify reusable actions, but you must verify that extracted methods don't couple pages that change independently.
Bad Fit: Single-Page Scripts
Avoid when: You are writing a one-off script for a single test that will never be reused. Guardrail: POM overhead adds maintenance cost without benefit for scripts with no shared page interactions. Use a simple helper function instead.
Bad Fit: Highly Dynamic UIs
Avoid when: The UI is generated at runtime with unpredictable structure, no stable attributes, and no design system. Guardrail: If even a human can't identify reliable selectors, the generated POM will be brittle. Invest in adding data-testid attributes to the application before automating.
Required Inputs
Minimum: UI description or existing script with selectors. Better: Component documentation, a screenshot, or a DOM snapshot. Best: All of the above plus a list of user flows that traverse the page. Guardrail: Missing inputs lead to hallucinated selectors. If you can't provide a DOM reference, mark the output as draft-only and plan a review session against the live application.
Operational Risk: Cross-Page Coupling
Risk: Generated POM classes may import other page objects or assume navigation state, creating tight coupling. Guardrail: Review every cross-page reference in the generated code. Each page object should be independently instantiable. Navigation should happen in the test, not inside the page object's action methods.
Copy-Ready Prompt Template
A copy-ready prompt template that generates a Page Object Model class from UI descriptions or existing test scripts, with encapsulated selectors, actions, and assertions.
This prompt template is designed for SDETs and automation engineers who need to scaffold maintainable Page Object Model (POM) classes. It takes a description of a UI component, page, or an existing brittle test script and produces a well-structured class with encapsulated selectors, action methods, and assertion helpers. The goal is to enforce separation of concerns, making tests more readable and less fragile by abstracting the UI's implementation details away from the test logic.
markdownYou are a senior SDET specializing in test automation architecture and the Page Object Model pattern. Your task is to generate a Page Object class based on the provided context. **INPUT CONTEXT:** [UI_DESCRIPTION_OR_EXISTING_SCRIPT] **TARGET LANGUAGE & FRAMEWORK:** [LANGUAGE_AND_FRAMEWORK, e.g., TypeScript with Playwright, Java with Selenium] **OUTPUT SCHEMA:** Generate a single, well-commented class that adheres to these rules: 1. **Encapsulated Selectors:** All element locators must be defined as private properties at the top of the class. Use a prioritized strategy: `data-testid` first, then accessible roles/labels, and finally stable CSS selectors. Do not use XPath unless absolutely necessary. 2. **Action Methods:** Public methods should represent high-level user actions (e.g., `login()`, `searchForProduct()`, `addItemToCart()`). Each method must return either `void` or a new Page Object representing the navigated-to page. 3. **Assertion Helpers:** Include public methods that return boolean promises or perform explicit assertions for common state checks (e.g., `isErrorMessageVisible()`, `getCartItemCount()`). These methods should not contain test logic. 4. **Explicit Waits:** Do not use `sleep()` or fixed delays. Use framework-native explicit wait strategies (e.g., Playwright's `waitForSelector`, Selenium's `WebDriverWait`) before any element interaction. 5. **Constructor:** The constructor should accept the test runner's page or driver instance and assert that a unique element on the page is visible to confirm navigation was successful. **CONSTRAINTS:** - Do not generate the test case itself, only the Page Object. - Keep methods focused on a single responsibility. - If the input describes a multi-step workflow, model each distinct page or state as a separate class suggestion in a comment. - Provide a brief comment at the top of the class explaining its responsibility boundary.
To adapt this template, replace the [UI_DESCRIPTION_OR_EXISTING_SCRIPT] placeholder with a detailed description of the UI component, a screenshot's text description, or the raw code of a script you want to refactor. The [LANGUAGE_AND_FRAMEWORK] placeholder should be a precise string like TypeScript with Playwright or Python with Selenium. After generating the POM, you should immediately review it for cross-page coupling risks and ensure the selectors are resilient to minor UI changes. The next step is to integrate this class into a test harness and validate it against a real environment.
Prompt Variables
Each placeholder required by the Page Object Model generation prompt, its purpose, a concrete example, and actionable validation rules to prevent brittle or incomplete POM classes.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[UI_DESCRIPTION] | Raw description of the UI component, page, or screen for which the POM class is being generated. Can be natural language, a screenshot transcript, or existing test step comments. | Login page with email field, password field, 'Sign In' button, 'Forgot Password' link, and inline error message region that appears conditionally. | Check that input is non-empty and contains at least one identifiable interactive element. Reject inputs that are pure code or unrelated prose. Minimum 50 characters required. |
[FRAMEWORK] | Target test automation framework for the generated POM class. Controls import statements, selector API style, and assertion library integration. | Playwright | Must match one of the allowed enum values: Playwright, Selenium, Cypress, WebDriverIO. Reject unknown values. Framework choice determines generated method signatures and wait strategy defaults. |
[LANGUAGE] | Programming language for the generated POM class. Controls syntax, type annotations, and module structure. | TypeScript | Must match one of the allowed enum values: TypeScript, JavaScript, Python, Java, C#. Reject unknown values. Language choice determines file extension, type strictness, and import style. |
[SELECTOR_STRATEGY] | Preferred selector priority order. Controls which locator types the model generates first and how fallback chains are constructed. | data-testid > aria-label > text content > CSS class | Validate that the strategy string contains at least two recognized selector types from the set: data-testid, aria-label, aria-role, text, placeholder, CSS, XPath, id, name. Reject strategies that rely solely on XPath or CSS class without fallback. |
[EXISTING_SCRIPT] | Optional existing test script or POM class that the generated output should extend, refactor, or remain consistent with. Used to enforce naming conventions and method signatures. | Existing login.spec.ts with hardcoded selectors and no POM abstraction. | If provided, validate that the input is parseable code in the target [LANGUAGE]. If null, the model should generate a greenfield POM class. When present, generated methods must not duplicate or conflict with existing public methods unless explicitly refactoring them. |
[RESPONSIBILITY_BOUNDARY] | Description of what this page object owns versus what belongs to child components, parent layouts, or cross-page workflows. Prevents bloated POM classes. | This POM owns only the login form. Header, footer, and post-login redirect are owned by LayoutPOM and DashboardPOM respectively. | Check that the boundary description explicitly names at least one out-of-scope element or behavior. If missing, flag a review warning: unbounded POM scope increases coupling risk. Generated class must not include selectors or methods for elements outside the stated boundary. |
[REUSE_TARGETS] | List of existing POM classes, utility helpers, or custom assertion libraries that the generated class should compose or extend rather than reimplementing. | BasePage class with shared navigate(), waitForLoad(), and screenshot() methods. | If provided, validate that each target name is a non-empty string. Generated code must import and use these targets rather than redefining equivalent functionality. If null, the model may generate self-contained classes. Review warning if generated class duplicates standard BasePage methods. |
Implementation Harness Notes
How to wire the POM generation prompt into a reliable, reviewable automation workflow.
The Page Object Model generation prompt is not a one-shot code generator you trust blindly. It is a scaffolding engine that produces a first draft of a POM class. The implementation harness around this prompt must enforce validation, human review, and integration checks before the generated code reaches a shared test repository. Treat the output as a structured suggestion, not a deployable artifact. The harness should capture the input context (UI description, existing test script, or component source), the raw model response, and any post-processing steps so that every generated POM is traceable to its origin.
Wire the prompt into a pipeline that performs at minimum three stages: schema validation, selector sanity checks, and responsibility boundary review. Schema validation should confirm the output parses as valid code in the target language (TypeScript, Python, Java) and contains the required structural elements: a class declaration, a constructor with locator initialization, at least one action method, and at least one assertion helper. Selector sanity checks should flag selectors that rely on unstable attributes like auto-generated CSS classes, absolute XPath indices, or text content that changes with localization. Responsibility boundary review is a manual or LLM-as-judge step that checks whether the generated POM mixes page concerns (navigation, multi-page workflows) that belong in a separate page object or test layer. Each stage should produce a pass/fail signal and a structured reason so the pipeline can decide whether to retry, flag for human review, or reject the output.
For model choice, prefer a model with strong code generation capabilities and structured output support. If your provider supports it, request the output in a typed JSON schema that maps to the POM structure rather than relying on freeform code blocks. This reduces parsing fragility. Set a low temperature (0.0–0.2) to minimize creative variation in selector strategies and method signatures. Implement a retry budget of two attempts: if the first output fails schema validation, feed the validation errors back into a retry prompt that includes the original input plus the specific failure reasons. If the second attempt also fails, escalate to a human reviewer with the input, both outputs, and the validation report. Log every generation attempt with the input hash, model version, output, validation results, and reviewer decision. This audit trail is essential when a generated POM later causes a flaky test and the team needs to trace its origin.
Do not allow generated POMs to be committed directly to the test repository without human approval. The harness should open a pull request or create a review task that includes the generated code, the selector chain with fallback rationale, and a diff against any existing page object for the same page. Reviewers should verify that action methods encapsulate wait strategies internally, that assertion helpers return boolean or assertion results rather than performing side effects, and that the POM does not import test-runner-specific assertions directly. After approval, run the generated POM through a smoke test that instantiates the class against a live or mocked page and calls each action method once. A POM that cannot survive a basic instantiation-and-call smoke test should not enter the repository, regardless of how clean the code looks.
Expected Output Contract
Validate the structure and content of the generated Page Object Model class against this contract. Each field must satisfy the specified validation rule before the output is accepted for integration.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
ClassName | PascalCase string | Must match pattern ^[A-Z][a-zA-Z0-9]+(Page|Modal|Component|Fragment)$. Reject if generic suffix like 'PageObject' is used. | |
SelectorMap | Object with string keys and string values | All keys must be camelCase. All values must be valid CSS or XPath strings. No hardcoded text selectors allowed unless wrapped in a fallback chain. | |
ActionMethods | Array of method signatures | Each method must have a return type of void, Promise<void>, or the POM class itself for chaining. Methods named 'clickX', 'typeX', or 'selectX' must accept only data types relevant to the action. | |
AssertionHelpers | Array of method signatures | If present, each method must return a boolean or assert without a return value. Method names must start with 'is', 'has', or 'assert'. Reject if assertion methods perform actions. | |
ConstructorParameters | Array of typed parameters | Must accept a Page or Driver object as the first parameter. Additional parameters are allowed only if documented with a purpose comment. Reject if constructor contains implicit waits or assertions. | |
WaitStrategy | Object or string | Must define explicit wait configurations per interaction type. Reject if 'sleep' or fixed-timeout calls are detected. Acceptable values: 'networkidle', 'visible', 'attached', or custom condition functions. | |
ErrorHandling | Try-catch blocks or null | If present, catch blocks must log the error and re-throw or return a sentinel value. Reject if catch blocks swallow exceptions silently or perform unrelated recovery actions. | |
ImportStatements | Array of strings | Must include imports for base page class, assertion library, and test runner. Reject if imports reference internal project paths without a configurable alias or if unused imports are present. |
Common Failure Modes
What breaks first when generating Page Object Models from prompts and how to guard against it.
Selector Brittleness
What to watch: The model generates CSS or XPath selectors tied to auto-generated class names, deeply nested DOM paths, or dynamic IDs that break on the next deploy. Guardrail: Require a prioritized selector strategy in the prompt (data-testid > aria-label > text content > stable CSS) and validate generated selectors against a static DOM snapshot before accepting.
Overloaded Page Objects
What to watch: The model merges actions for multiple distinct UI sections into a single monolithic class, creating a maintenance nightmare. Guardrail: Include explicit responsibility boundaries in the prompt template, such as 'one page object per distinct UI region or route,' and review the generated class for methods exceeding a single concern.
Missing Wait Strategies
What to watch: Generated action methods assume elements are immediately available, producing scripts that fail under normal network latency or asynchronous rendering. Guardrail: Append a system instruction requiring every action method to include an explicit, condition-driven wait (e.g., waitForSelector) before interaction, and reject any method that calls .click() without a preceding wait guard.
Hardcoded Test Data in POM
What to watch: The model embeds example strings, URLs, or credentials directly into the page object instead of accepting them as method parameters, making the class unreusable across environments. Guardrail: Add a validation step that scans the generated code for string literals outside of selector definitions and flags them for extraction into method arguments or a data provider.
Cross-Page Coupling
What to watch: A generated page object's method instantiates or directly references another page object to model navigation, creating a hidden dependency chain that breaks when either page changes. Guardrail: Enforce a rule that navigation methods must return a new page object instance only after confirming successful navigation, and never import sibling page objects directly. Review for new OtherPage() calls inside action methods.
Assertion Logic Inside Actions
What to watch: The model mixes verification assertions into action methods, causing tests to fail during setup or navigation instead of at explicit checkpoints. Guardrail: Instruct the prompt to separate 'action methods' (return void or a page reference) from 'assertion helpers' (return boolean or throw). A post-generation lint check should flag any expect or assert call inside a method named with an action verb like click, fill, or navigate.
Evaluation Rubric
Use this rubric to evaluate the quality of a generated Page Object Model before integrating it into your test suite. Each criterion targets a specific failure mode common in AI-generated POMs.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Selector Resilience | All selectors use data-testid, aria-label, or role-based locators. No XPath or CSS classes tied to styling. | Presence of CSS class selectors (e.g., '.btn-primary') or XPath expressions containing style attributes. | Static analysis: regex scan for forbidden selector patterns in the generated file. |
Method Responsibility Boundary | Each method performs one interaction or one assertion. No method mixes navigation, interaction, and assertion. | A method named 'loginAndVerifyDashboard' that clicks a button and then asserts page URL. | LLM-as-Judge: prompt a reviewer model to identify methods with mixed concerns using the method body. |
Wait Strategy Completeness | Every action method that triggers a navigation or UI update is followed by an explicit wait for a post-condition. | A 'clickSubmit' method that returns immediately without waiting for a success toast or URL change. | Static analysis: verify that methods containing 'click' or 'fill' are followed by 'waitFor' or assertion calls within the same block. |
Return Type Consistency | Action methods return a reference to another POM class for chaining or void. No raw page objects or generic types returned. | An action method returning 'this.page' or 'any'. | TypeScript compiler check: run |
Cross-Page Coupling Risk | The POM imports only its own page's selectors and direct child component POMs. No imports from sibling or parent pages. | A 'CheckoutPage' POM importing 'HomePage' to navigate back. | Dependency graph analysis: generate import graph and flag any cycle or import from a non-child page object. |
Assertion Helper Encapsulation | Reusable assertion logic is extracted into private helper methods within the POM. No assertion logic is duplicated across test files. | The same 5-line visibility check is copy-pasted into three different test scripts. | LLM-as-Judge: prompt a reviewer model to compare assertion blocks across the POM and sample test files for duplication. |
Error State Handling | At least one method exists to verify the page's error or empty state. The POM does not assume only happy-path rendering. | A POM for a search results page with no method to verify the 'No results found' message. | Schema check: validate that the POM class contains at least one method with 'Error' or 'Empty' in its name. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base prompt and a single page description. Remove strict output schema requirements and accept a plain class outline. Use a lighter model for fast iteration.
codeGenerate a Page Object class for [PAGE_NAME] with: - Selectors for [ELEMENT_LIST] - Action methods for [USER_ACTIONS] - Basic assertion helpers Return the class in [LANGUAGE] without strict validation.
Watch for
- Hardcoded selectors without fallback chains
- Missing wait strategies on action methods
- Methods that mix navigation, assertion, and interaction responsibilities
- Overly broad selectors that will break on minor DOM changes

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us