Chapter 05 · Software Testing with AI Automation
Locators, Assertions and Waits
Flaky tests usually mean weak locators or missing waits — not “Playwright is bad”.
Why this matters
Unstable suites slow CI and make teams ignore failures. Good locators (role, label, test id) and assertions that wait for the UI keep trust high.
What you will learn
You will prefer getByRole / getByLabel, assert visibility and text, and replace waitForTimeout with expect-driven waits.
How to do it
Follow Playwright’s locator guidance. Add data-testid only when roles/labels are not enough.
Steps (do these in order)
- Step 1 — Prefer roles. getByRole('button', { name: 'Sign in' }) beats brittle CSS like div.btn-xyz-12.
- Step 2 — Assert with expect. await expect(page.getByText('Welcome')).toBeVisible() — Playwright waits until timeout.
- Step 3 — Avoid hard sleep. Delete waitForTimeout(5000) unless you are debugging. Prefer expect or locator.waitFor.
- Step 4 — Test id escape hatch. If the UI has no accessible name, ask developers for data-testid="login-email".
- Step 5 — One flake drill. Break a locator on purpose, see the error, then fix it — learn to read the failure.
Practice
- Rewrite one CSS-selector test to role/label locators.
- Write three assertions for a successful login banner.