Generate a Cypress Page Object Model with AI
Returns a Cypress Page Object class using cy.get() with data-cy preference, action methods that chain via `return this`, plus a commands.js file for cross-page utilities and a sample spec consuming the POM.
When to use it
- Starting a new Cypress suite and need a consistent POM scaffold.
- Migrating selectors from CSS/XPath to data-cy testid convention.
- Comparing Cypress vs Playwright POM patterns for an architecture decision.
- Standardizing custom commands across multiple page objects.
The prompt
<role>You are a senior Cypress automation engineer with deep experience in the Cypress chained command model and custom command registration. You enforce data-cy testid convention and reject CSS selectors except as last resort.</role> <context>The team uses Cypress 14+ with JavaScript (TypeScript optional). POMs are classes with action methods that return `this` (for chaining) and use `cy.get('[data-cy=...]')` as the primary locator strategy. Cross-page utilities live in `cypress/support/commands.js` and are registered with `Cypress.Commands.add`.</context> <task>Generate a complete Cypress Page Object Model for the page below, including:1. A class with action methods that chain via `return this`2. `cy.get('[data-cy=...]')` selectors (CSS only as last resort)3. Assertion methods using `.should('be.visible')` and similar4. A `visit()` method5. A separate `commands.js` snippet registering 1-2 reusable custom commands the page object would benefit from6. A sample spec file showing the POM in use</task> <input>Page name: {page_name}Page URL path: {url_path}Elements (label → data-cy testid):{element_list} User intents on this page:{intents}</input> <constraints>- Cypress 14+ syntax.- Primary locator: `cy.get('[data-cy=<id>]')`. CSS only when data-cy is impossible.- Action methods return `this` for chaining.- No `cy.wait(<ms>)` hard waits.- Custom commands MUST be in a separate `commands.js` snippet, not inline in the POM.</constraints> <output_format>Three code blocks:1. The POM class (e.g., `cypress/support/pages/LoginPage.js`)2. Custom commands (`cypress/support/commands.js` snippet)3. Sample spec consuming the POMFollowed by 3-5 "Next steps" bullets (e.g., add data-cy attrs to the app, wire commands.js, etc.).</output_format> <approach>Before writing, decide which actions naturally chain and which need separate calls.</approach>## RoleSenior Cypress automation engineer. Cypress 14+, chained command model, custom commands. ## ContextJavaScript (TypeScript optional). POMs are classes with chaining action methods (`return this`). Primary locator: `cy.get('[data-cy=...]')`. Custom commands in cypress/support/commands.js. ## TaskGenerate a complete Cypress POM with: chaining action methods, data-cy selectors, `should`-based assertions, `visit()`, a commands.js snippet with 1-2 custom commands, and a sample spec. ## Input- Page name: {page_name}- URL path: {url_path}- Elements: {element_list}- User intents: {intents} ## Constraints- Cypress 14+ syntax.- Primary locator: data-cy. CSS only if impossible.- Action methods return `this`.- No `cy.wait(<ms>)` hard waits.- Custom commands in separate file, not inline. ## Output formatThree code blocks (POM class, commands.js snippet, sample spec) + 3-5 "Next steps" bullets. ## ApproachDecide which actions chain vs which need standalone calls before writing.Example
Input
Page name: Login URL path: /login Elements: - Email input → data-cy="login-email" - Password input → data-cy="login-password" - Submit button → data-cy="login-submit" - Forgot password link → data-cy="login-forgot" - Error banner → data-cy="login-error" User intents: - Log in with valid credentials - Log in with invalid credentials and verify error - Navigate to forgot-password flow
Output
```javascript
// cypress/support/pages/LoginPage.js
export class LoginPage {
visit() {
cy.visit('/login');
cy.get('[data-cy=login-email]').should('be.visible');
return this;
}
fillEmail(email) {
cy.get('[data-cy=login-email]').type(email);
return this;
}
fillPassword(password) {
cy.get('[data-cy=login-password]').type(password, { log: false });
return this;
}
submit() {
cy.get('[data-cy=login-submit]').click();
return this;
}
signIn(email, password) {
return this.fillEmail(email).fillPassword(password).submit();
}
openForgotPassword() {
cy.get('[data-cy=login-forgot]').click();
return this;
}
assertErrorVisible(message) {
cy.get('[data-cy=login-error]').should('be.visible');
if (message) cy.get('[data-cy=login-error]').should('contain.text', message);
return this;
}
}
```
```javascript
// cypress/support/commands.js
Cypress.Commands.add('loginAs', (email, password) => {
cy.session([email, password], () => {
cy.request('POST', '/api/login', { email, password });
});
});
Cypress.Commands.add('byTestId', (id) => cy.get(`[data-cy=${id}]`));
```
```javascript
// cypress/e2e/login.cy.js
import { LoginPage } from '../support/pages/LoginPage';
describe('Login', () => {
const login = new LoginPage();
it('signs in with valid credentials', () => {
login.visit().signIn('alice@example.com', 'Pass1234');
cy.url().should('include', '/dashboard');
});
it('shows an error for invalid credentials', () => {
login.visit().signIn('alice@example.com', 'wrong');
login.assertErrorVisible('Invalid credentials');
});
it('navigates to forgot password', () => {
login.visit().openForgotPassword();
cy.url().should('include', '/forgot-password');
});
});
```
Next steps:
- Confirm `data-cy` attributes exist on the production markup.
- Import `commands.js` from `cypress/support/e2e.js`.
- For TypeScript projects, add type declarations for `loginAs` and `byTestId` to `cypress.d.ts`.
- Consider replacing `cy.request` in `loginAs` with a real login flow if API endpoint changes.Common pitfalls
- Model produces Playwright-style async/await disguised as Cypress: Cypress commands are not awaited. Re-prompt with explicit Cypress version mention.
- Custom commands sometimes leak into the POM class body: enforce separate commands.js in constraints.
- Without data-cy emphasis, model defaults to class/text selectors, brittle to CSS changes.
- Action methods may forget `return this`, breaking chaining for downstream callers.
Tips
- Add `cy.session()` patterns in commands.js for any login flow: massive speedup for suites with auth.
- Pair this POM pattern with `should('not.exist')` for negative assertions; Cypress retries it correctly.
- If your app doesn't have data-cy attrs yet, generate the POM first, then add the attrs to the app one by one as you implement.
- Use Cypress Cloud parallel runs: the POM structure doesn't need changes; only spec sharding does.
FAQ
Should I use Cypress or Playwright in 2026?
Playwright has overtaken Cypress for new projects due to faster execution, multi-tab support, and better mobile emulation. Cypress remains strong for existing teams already invested. Both can produce great test suites: the framework is rarely the bottleneck.
Why prefer data-cy over CSS or text selectors?
data-cy attributes are explicitly added for tests, so they don't break when designers change classes or copywriters change text. Cypress's own Best Practices guide recommends this approach. Use it from day one: retrofitting is painful.
Can I use TypeScript with this POM pattern?
Yes: add types to constructor params, return values, and the custom commands declaration in cypress.d.ts. The structural pattern stays identical.
How is Cypress chaining different from Playwright's async/await?
Cypress queues commands; you don't await them. Playwright executes promises sequentially with await. In Cypress, `return this` from POM methods lets you chain `.fillEmail().fillPassword().submit()`. In Playwright, each POM method is async and awaited on its own: `await loginPage.fillEmail(email)`.