POMs with AI

Let your agent extract repeated locators into a Page Object Model.

You drove a flow and generated tests in lesson 2. The next two lessons go one step further. Instead of asking the agent to write a test, you ask it to restructure what's already there. Page Object Models (POM) and fixtures are the two refactorings I use most. Both are repetitive busywork, which makes them perfect for an agent.

What is a Page Object Model?

When the same locators show up across multiple tests, a Page Object Model pulls them into one place. POMs are classes that hold the locators for a single page and offer methods for the meaningful actions on it.

A good POM is a handful of locators with action methods on top:

Page Object Model
tests/poms/product-page.ts
import type { Page, Locator } from "@playwright/test";

export class ProductPage {
  readonly page: Page;
Locatorsnames + queries
  readonly addToCartButton: Locator;
  readonly title: Locator;
  readonly price: Locator;

  constructor(page: Page) {
    this.page = page;
    this.addToCartButton = page.getByLabel("Add item to cart");
    this.title = page.getByRole("heading", { level: 1 });
    this.price = page.getByTestId("price");
  }
Actionsverbs
  async goto(handle: string) {
    await this.page.goto(`/product/${handle}`);
  }

  async addToCart() {
    await this.addToCartButton.click();
  }
}
A spec using it
tests/snowboard.spec.ts
import { test, expect } from "@playwright/test";import { ProductPage } from "./poms/product-page"; test("adds a snowboard to the cart", async ({ page }) => {  const product = new ProductPage(page);   await product.goto("snowboard");  await expect(product.title).toContainText(/snowboard/i);  await product.addToCart();});

Once the class exists, every spec that touches the product page needs three lines instead of thirty.

Let the agent do the extraction

Drafting a POM class is repetitive pattern matching, and that's exactly the work an agent is good at.

Ask your agent to read your existing spec files, find the locators they share, and move them into a class.


Hands on

Hand the POM extraction to the agent

Exercise 1 of 1

Extract a ProductPage POM

Identify the specs in your repo that touch a product detail page (the snowboard test from lesson 2 and the cart spec are good candidates). Try drafting the prompt yourself first, then reveal the one below to compare. Validate the generated class.

Are the methods actions or thin getters? If the class survives your review, apply it and re-run both tests.

Show an example prompt

Can you take the existing spec.ts files and refactor them to use page object models (POMs)? Extract proper pages and place them in tests/poms/ with action methods (not locator getters). Use the Playwright CLI to evaluate for correctness!

Read the Playwright docs for an example: https://playwright.dev/docs/pom.

Prompt for your coding agent