One wrong locator, copied into three tests, is four places to fix, and every new test adds another copy. This lesson gathers those lines in one place, a page object, and measures what that really buys you, with one question: when a locator breaks, how many places do I touch? It follows the official docs (Page object models, Strictness, Fixtures), and every command and output comes from a real run.
What you need
- Node.js. 22, 24, 26.
- Playwright 1.65.1. The lesson was recorded with this version; other versions may print slightly different output.
- The code. Subscribers see the lesson repository in the Source code box under the video, with the tags
pw06-startandpw06-end.
The demo runs against automationexercise.com, which sometimes shows a waiting page to automated browsers; if a test fails on the page title, run it again a little later. In the lesson repository these tests run in the site-pom project.
Step 1: Four places to fix
tests/duplicate.spec.ts has three cart tests. Every test opens the products page, waits for the title, then clicks Add to cart through the data-product-id attribute. The line is copied four times in three tests, because add two items clicks twice.
npx playwright test tests/duplicate.spec.ts --project=site-pom --workers=1
Fails on purpose.
duplicate.spec.tsis red by design.
All three tests fail with the same message: strict mode violation, resolved to 2 elements. Four copies, all wrong in the same way. One wrong line, four places to fix.
Step 2: Where does the second button come from?
The error log lists both elements it found and suggests a locator for each (first and nth(1)): two identical a tags. Hover over a product card: an orange overlay appears with a second Add to cart button on it, with the same data-product-id. Counting with Playwright confirms it: count is 2. The Strictness section of the Locators page explains why the test stops: locators are strict, and any operation that needs one element throws if more than one matches.
The fix is to put the productinfo class in front, which takes only the main card's button:
await page.locator('.productinfo [data-product-id="1"]').click();
npx playwright test tests/duplicate-fixed.spec.ts --project=site-pom --workers=1
Three green tests. But the bug was never inside one test. It was in the duplication.
Step 3: A drawer for every page
The Page object models docs say it in one line: each part of your web app gets a page object, and selectors live in one place. Picture a cabinet with one drawer per page. In the project each drawer is a file in tests/pages/: ProductsPage.ts, CartPage.ts, and later LoginPage.ts and Header.ts. A page object is a plain class, with no extra library:
export class ProductsPage {
readonly viewCart: Locator;
readonly keepShopping: Locator;
constructor(readonly page: Page) {
this.viewCart = page.getByRole('link', { name: 'View Cart' });
this.keepShopping = page.getByRole('button', { name: 'Continue Shopping' });
}
async goto() {
await this.page.goto('/products');
await expect(this.page).toHaveTitle(/All Products/);
}
async add(id: number) {
await this.page.locator(`.productinfo [data-product-id="${id}"]`).click();
}
}
The locators are at the top, what you can do on the page is below. The test shrinks to one call, products.add(1), and reading the test is reading the scenario.
Step 4: Which locator for which drawer?
Lesson 3 recommended getByRole, so why does this drawer use CSS? Measure on the products page instead of guessing:
| Locator | Matches on the products page |
|---|---|
data-qa attributes | none |
getByRole('link', { name: 'Add to cart' }) | 0: ariaSnapshot shows the button is an a tag with no href, so Playwright sees text, not a link |
getByText('Add to cart') | 68: 34 cards, two buttons each |
CSS by data-product-id | 2 |
CSS with .productinfo in front | exactly 1 |
The login page is different: six data-qa attributes are ready, so its drawer uses getByTestId. Pick locators by what the page offers. And since it lives in a drawer, changing your mind later is still one edit.
Step 5: Is the code shorter? Are the tests less red?
Counting lines, the duplicated version is one file and the page object version, with ProductsPage, CartPage and the test file, is almost three times longer. So what does writing more buy you? Run the page object version, tests/pom.spec.ts, still with the wrong locator in the drawer: three tests, still red, still strict mode violation. A wrong locator is still wrong. Moving it does not fix it.
But look at the error frame: it points inside the drawer, at the line in tests/pages/ProductsPage.ts, and the line below it is the test that called it. Three red tests, all pointing at one line. Fix exactly one line in that drawer, add .productinfo, and run again:
npx playwright test tests/pom.spec.ts --project=site-pom --workers=1
All three green at once.
| Duplicate code | Page object | |
|---|---|---|
| Copies of the locator | 4, in 3 tests | 1, in 1 file |
| Places to fix | 4 | 1 |
With three tests the gain is small. With thirty tests, the left side is thirty places to remember.
Step 6: Does a page object find elements right away?
Last belief to test: does creating a page object make Playwright look for elements? CartPage has a rows locator. tests/lazy.spec.ts creates it while the page is still blank, before any goto, and counts:
npx playwright test tests/lazy.spec.ts --project=site-pom --workers=1
The url is about:blank, rows is 0, and there is no error. Go to the cart page with the same page object and empty is true. The constructor only records how to find things; the finding happens when you use the locator. Creating the page object at the start of a test is fine.
Step 7: Hand the page objects to tests with a fixture
Now every test starts with two lines, new ProductsPage and new CartPage: duplication again, just smaller. The fixtures docs show the fix: a fixture that returns a page object. tests/fixtures.ts builds each page object from page and hands it over with use, the same tray as lesson 5:
products: async ({ page }, use) => {
await use(new ProductsPage(page));
},
Tests now ask for products and cart in the braces of the test: no imports, no new.
npx playwright test tests/pom.spec.ts tests/fixture.spec.ts --project=site-pom --workers=1
Six green tests (three with page objects built by hand, three with fixtures). In this lesson the fixtures file also has loginPage and an account fixture like the one from lesson 5; lesson 5's own files were renamed fixtures-account.ts and fixture-account.spec.ts to make room.
Step 8: A third drawer, and the header
LoginPage uses getByTestId for email, password and the Login button, and its login method takes one object, { email, password }, so a test can pass the account fixture straight in. For a wrong password, copy the object and change one field.
npx playwright test tests/header.spec.ts tests/login.spec.ts --project=site-pom --workers=1
Three tests pass: header to cart, login shows name, and wrong password, which sees exactly Your email or password is incorrect!.
The login test reads Logged in as, and that line lives in the header, which every page has. Which drawer does it go in? Two options, and both run green (tests/alt/ has the inheritance one):
| Option | How | Limit |
|---|---|---|
| Inheritance | a BasePage holds the header links and ProductsPage extends it | a TypeScript class can extend only one class |
| Composition | a separate Header class, and each page keeps a header property | tomorrow's footer or cart dialog is just one more piece |
Composition wins: in the test, products.header.cart reads exactly where that button lives.
Step 9: What goes in the drawer?
Each page's locators and actions go into that page's drawer. Shared pieces like the header are composed in. A rule: an expect that is what the test proves stays in the test. An expect that only waits for the page to load goes in the drawer.
Tests that fail on purpose
| File | Fails because |
|---|---|
duplicate.spec.ts | the unscoped locator matches two elements (strict mode violation) |
Check your result
npx playwright test tests/duplicate.spec.ts --project=site-pom --workers=1→ 3 failednpx playwright test tests/pom.spec.ts tests/fixture.spec.ts --project=site-pom --workers=1→ 6 passed
Recap
| Question | Answer |
|---|---|
| Does a page object make tests less red? | No, a wrong locator is still wrong |
| What does it change? | The place to fix is one, not many |
| Does it find elements early? | No, locators are lazy |
| Inheritance or composition for the header? | Composition |
- Four copies of a wrong locator are four places to fix; in a page object it is one.
- Pick the locator by what the page offers, and measure before you choose.
- Hand page objects to tests with fixtures instead of
newin every test. - Compose shared pieces like the header; a class can extend only one class.
Next lesson
One annoyance remains: every test that needs a login goes through the login form from scratch. Next, can you log in once for the whole suite? We configure Playwright, starting with storageState.