Page Objects & Fixtures
One long test is easy. Fifty are not. Move the page details into classes and the setup into fixtures, as real test suites do.
Structuring a test suite
A Page Object describes what a customer can do
Locators live in one place. When the page changes, one file changes, not fifty tests. Name methods after the action, not the click.
export class CartPage {
readonly total: Locator;
constructor(private readonly page: Page) {
this.total = page.getByTestId('cart-total');
}
async applyPromo(code: string) {
await this.page.getByLabel('Promo code').fill(code);
await this.page.getByRole('button', { name: 'Apply' }).click();
}
}Keep assertions in the tests. A Page Object says how to do something; the test says what should be true.
Fixtures hand a test what it needs
export const test = base.extend<{ cart: CartPage }>({
cart: async ({ page }, use) => {
await use(new CartPage(page));
},
});
test('applies a code', async ({ cart }) => { … });Skip the slow parts through the API
Only one test needs to sign in through the form. The others can get a token from the API and place it where the app looks for it, before the page loads:
const response = await request.post('/api/shop/login', { data: { email, password } });
const { token } = await response.json();
await page.addInitScript((value) => {
localStorage.setItem('qa-shop-token', value);
}, token);Parallel tests must not share anything
Every worker runs at the same time. Give each test its own cart and, when it changes an account, its own account.
The shop
QA Electronics runs at /shop. Nothing is really sold, and each browser context gets its own cart.
Accounts
| Password | What it has | |
|---|---|---|
| alex@example.com | Password1 | A saved address and past orders |
| locked@example.com | Password1 | A locked account |
Promo codes
| Code | Effect |
|---|---|
| SAVE10 | 10% off |
| WELCOME20 | $20 off orders of $200 or more |
| FREESHIP | Free standard delivery |
| SUMMER25 | Expired |
Test cards
Use any future expiry date, such as 12/30, and any 3-digit CVC.
| Card number | Result |
|---|---|
| 4111 1111 1111 1111 | Success (Visa) |
| 4242 4242 4242 4242 | Success (Visa) |
| 5555 5555 5555 4444 | Success (Mastercard) |
| 4000 0000 0000 0002 | Declined |
| 4000 0000 0000 9995 | Insufficient funds |
| 4000 0000 0000 0069 | Expired card |
| 4000 0000 0000 3220 | Bank asks to confirm (3-D Secure) |
| 4000 0000 0000 0119 | Provider times out after 6 seconds |
Next in Mini Shop · 3 of 4Checkout Edge Cases →Cover what can go wrong between the cart and the order.
Related exercises
- Mini ShopIntermediateFirst E2E TestWrite your first full end-to-end test: a guest finds a laptop, pays, and gets a confirmation.
- AuthenticationAdvancedSign In & SessionsTest a sign-in session, then reuse it so other tests start signed in.
- Mini ShopAdvancedUI + API TogetherCombine the API and the browser for tests that are fast, independent and thorough.
Read the guide: Playwright Page Object Model with fixtures