Module 3. Practice: from requirements to automated tests · Lesson 26 of 41 · 20 min
Your first Playwright tests: locators, assertions, hooks and fixtures
From npm init to a stable suite: test structure, role-based locators, auto-waiting, beforeAll/beforeEach/afterEach/afterAll, fixtures and Page Object.
Setup
npm init playwright@latest
npx playwright test # run
npx playwright test --ui # interactive mode
npx playwright show-report # HTML report
The first test for US-214
import { test, expect } from "@playwright/test";
test("promo code SALE10 takes 10% off the total", async ({ page }) => {
await page.goto("/cart");
await page.getByLabel("Promo code").fill("SALE10");
await page.getByRole("button", { name: "Apply" }).click();
await expect(page.getByTestId("cart-total")).toHaveText("$112.50");
await expect(page.getByText("10% discount applied")).toBeVisible();
});
Locators: from best to worst
| Priority | Locator | Why |
|---|---|---|
| 1 | getByRole("button", { name: "Apply" }) | How the user and a screen reader see it |
| 2 | getByLabel("Promo code") | Ties the field to its label |
| 3 | getByTestId("cart-total") | A stable attribute for tests |
| 4 | getByText("…") | Breaks when copy changes |
| 5 | CSS / XPath | Breaks when the layout changes |
Assertions like expect(...).toHaveText, toBeVisible and toHaveURL wait on their own for the expected state until the timeout — so no waitForTimeout(3000).
Hooks
import { test, expect } from "@playwright/test";
import { api } from "./helpers/api";
let userToken: string;
test.beforeAll(async () => {
userToken = await api.login("qa+promo@example.com"); // once per file
});
test.beforeEach(async ({ page }) => {
const cart = await api.createCart(userToken, [{ sku: "TSHIRT-M", qty: 1 }]); // a fresh cart per test
await page.goto("/cart/" + cart.id);
});
test.afterEach(async ({ page }, testInfo) => {
if (testInfo.status !== testInfo.expectedStatus) {
await page.screenshot({ path: testInfo.outputPath("failure.png"), fullPage: true });
}
});
test.afterAll(async () => {
await api.cleanupUser(userToken); // clean up after yourself
});
Hook rules:
- beforeEach creates data for a single test — tests don't depend on each other and can run in parallel.
- beforeAll — only for expensive, unchanging things (login, reference data).
- afterEach / afterAll clean up what was created so the environment doesn't get cluttered.
- Data is prepared through the API, not by clicking through the UI — 10–50 times faster.
Fixtures: reusable hooks
// fixtures.ts
import { test as base } from "@playwright/test";
import { api } from "./helpers/api";
export const test = base.extend<{ cartPage: { id: string } }>({
cartPage: async ({ page }, use) => {
const token = await api.login("qa+promo@example.com");
const cart = await api.createCart(token, [{ sku: "TSHIRT-M", qty: 1 }]);
await page.goto("/cart/" + cart.id);
await use(cart); // the test runs here
await api.deleteCart(token, cart.id); // and this runs after it
},
});
A test simply asks for the fixture: test("…", async ({ page, cartPage }) => { … }).
Page Object
When steps repeat across many tests, move them into a class:
export class CartPage {
constructor(private page: Page) {}
promo = () => this.page.getByLabel("Promo code");
async applyPromo(code: string) {
await this.promo().fill(code);
await this.page.getByRole("button", { name: "Apply" }).click();
}
total = () => this.page.getByTestId("cart-total");
}
Traces
Set trace: "on-first-retry" in the config: a failure produces a trace.zip with DOM snapshots, network and console for every step. Open it with npx playwright show-trace trace.zip.
The architecture of a large framework is covered in test automation architecture.
Key takeaways
- Role- and label-based locators are more stable than CSS and XPath.
- beforeEach creates data for each test — tests stay independent and parallel.
- Fixtures combine setup and cleanup in one reusable block.
Check yourself
1. Where should you create a cart with an item so tests don't depend on each other?
2. Why not write waitForTimeout(3000)?
3. What does the code after await use(cart) in a fixture do?