Playwright Page Object Model with fixtures
A first end-to-end test is one long list of locators and clicks. The second test repeats half of them. By the tenth, a renamed button means editing ten files.
Page Objects put the locators for each page in one place. Fixtures hand those objects to your tests and prepare the state a test starts from. This guide builds both for a small online shop, the Mini Shop on this site.
Start from a long test
Don't begin with classes. Write the whole purchase as one test first: search, add to cart, check out and pay. You need to see which steps repeat before you can decide what to extract.
Move to Page Objects when a second or third test needs the same steps, or when one change to the page makes you edit several tests.
- First E2E TestIntermediateWrite the long version: one test from search to order confirmation.
A Page Object class
A Page Object is a class that takes the page and offers one method per thing a user does there. Name the methods after the user's intent, such as search() and addToCart(), not after the clicks.
import type { Locator, Page } from '@playwright/test';
export class CataloguePage {
readonly total: Locator;
readonly cartCount: Locator;
constructor(private readonly page: Page) {
this.total = page.getByTestId('product-total');
this.cartCount = page.getByTestId('cart-count');
}
async open() {
await this.page.goto('/shop');
}
async search(text: string) {
await this.page.getByRole('searchbox', { name: 'Search products' }).fill(text);
await this.page.getByRole('button', { name: 'Search' }).click();
}
async addToCart(productName: string) {
await this.page
.getByRole('list', { name: 'Products' })
.getByRole('listitem')
.filter({ hasText: productName })
.getByRole('button', { name: 'Add to cart' })
.click();
}
}The test no longer knows how a product is found or which button adds it. When the shop changes its markup, you fix one method.
Keep the assertions in the test
Notice what the class doesn't have: expect. It exposes locators as fields, and the test asserts on them:
await catalogue.search('Wireless Mouse');
await expect(catalogue.total).toHaveText('1 product');
await catalogue.addToCart('Wireless Mouse');
await expect(catalogue.cartCount).toHaveText('1');There are two reasons to do it this way:
- The test reads as a specification. Everything it checks is visible in the test, not hidden in a method called
verifyCart(). - The same object serves the test that expects one product and the test that expects none.
Return locators, not values. A method like getTotal(): Promise<string> reads the text once, at whatever moment it runs. expect(locator).toHaveText() retries until the text is right. The auto-waiting guide explains the difference.
Create the objects in fixtures
Writing new CataloguePage(page) at the top of every test is repetition too. A fixture creates the object and passes it to any test that asks for it by name:
// tests/support/fixtures.ts
import { test as base } from '@playwright/test';
import { CartPage, CataloguePage, CheckoutPage } from './shop-pages';
type ShopFixtures = {
catalogue: CataloguePage;
cart: CartPage;
checkout: CheckoutPage;
};
export const test = base.extend<ShopFixtures>({
catalogue: async ({ page }, use) => use(new CataloguePage(page)),
cart: async ({ page }, use) => use(new CartPage(page)),
checkout: async ({ page }, use) => use(new CheckoutPage(page)),
});
export { expect } from '@playwright/test';Tests import test from this file instead of from @playwright/test:
import { expect, test } from './support/fixtures';
test('a guest buys a mouse', async ({ catalogue, cart, checkout }) => {
await catalogue.open();
await catalogue.search('Wireless Mouse');
await catalogue.addToCart('Wireless Mouse');
// …
});Fixtures are created only for the tests that name them. A test that asks for cart alone never builds the other objects.
Fixtures that prepare state
A test of the checkout shouldn't have to search the catalogue and click "Add to cart" first. Those steps are slow, and when the catalogue breaks, the checkout test fails for the wrong reason. Put the starting state in place through the API:
fillCart: async ({ page, request }, use) => {
await use(async (...slugs: string[]) => {
const cartId = crypto.randomUUID();
for (const slug of slugs) {
await request.post('/api/shop/cart/items', {
headers: { 'X-Shop-Cart': cartId },
data: { slug },
});
}
// Runs before the page's own scripts, on every navigation.
await page.addInitScript((value) => localStorage.setItem('qa-shop-cart', value), cartId);
});
},The fixture gives the test a function, so the test decides what goes in the cart:
test('a filled cart goes straight to the total', async ({ fillCart, cart }) => {
await fillCart('wireless-mouse', 'usb-c-hub');
await cart.open();
await expect(cart.items).toHaveCount(2);
await expect(cart.total).toHaveText('$78.00');
});Signing in works the same way: post the credentials to the API, then put the token where the app looks for it. The authentication guide covers that pattern.
- Page Objects & FixturesAdvancedBuild the Page Objects, then a signIn and a fillCart fixture.
- UI + API TogetherAdvancedPlace an order through the API and check it in the browser.
Keep the tests independent
Look at the first line of that fixture again: every test gets a cart id of its own. Two tests running at the same moment can't see each other's products. That's what allows the suite to run in parallel:
npx playwright test --workers=4If a suite passes with one worker and fails with four, some tests share data: an account, a cart or a record they all edit. Give each test its own data and don't force the tests to run in order.
- Page Objects & FixturesAdvancedRun the suite with four workers and confirm nothing collides.
- Checkout Edge CasesAdvancedReuse the same objects for declined cards and a payment outage.
When a function is enough
Not everything needs a class. A flow you repeat on one page is often clearer as a plain function at the top of the test file:
async function addNote(page: Page, title: string) {
await page.getByLabel('Note title').fill(title);
await page.getByRole('button', { name: 'Add note' }).click();
}Fixtures aren't only for Page Objects either. One marked { auto: true } runs for every test without being named. That suits jobs every test needs, such as collecting the page's console errors and attaching them to the report.
- Multi-step FormAdvancedHelper functions that take a test to step two or three of a sign-up.
- Debugging ToolkitAdvancedAn automatic fixture that records console messages and page errors.
Mistakes to avoid
- Extracting too early. An object written before the second test exists usually has the wrong methods.
- Methods named after clicks.
clickSearchButton()breaks when search starts on Enter.search(text)doesn't. - Hiding waits and
force: truein methods. A sleep inside a Page Object slows every test that uses it, and nobody sees it in review. - One class per URL, whatever the page looks like. A header or cart widget that appears on every page deserves an object of its own.
- A
BasePagethat everything extends. Shared behaviour fits better in a fixture or a helper than in an inheritance chain.
Exercises in this guide
- Page Objects & FixturesAdvanced
- UI + API TogetherAdvanced
- Checkout Edge CasesAdvanced
- First E2E TestIntermediate
- Multi-step FormAdvanced
- Debugging ToolkitAdvanced
More guides
- Playwright practice for beginners: a four-week plan
- Playwright locators: a practical guide with exercises
- Playwright auto-waiting: how to fix flaky tests
- Testing iframes with Playwright
- Playwright network mocking and API testing
- Playwright authentication: sign in once with storageState
- File upload and download in Playwright
- Playwright Trace Viewer: how to debug failing tests
- Running Playwright tests in CI with GitHub Actions
- Playwright cheat sheet: locators, actions and assertions