A UI Test with Playwright
Why This Matters
UI tests are the only tests that see the application as a user does: in a real browser, with the real page. They are also the slowest and the most fragile. So you write few of them, for the flows that matter most, and you make them robust.
Record a first draft
Playwright can record what you do in the browser and turn it into test code. The Playwright documentation on test generation explains it:
Screenshot of playwright.dev.
With TestRun Board running (npm run dev), in a second terminal:
npx playwright codegen http://localhost:5173
Click around, then copy the generated code. AI assistants can do the same through browser tools (for example the Playwright MCP server): they open the page, look at it and write the test. Either way, you get a draft, not a finished test.
What a good UI test looks like
TestRun Board already has one. Open tests/e2e/runs-page.spec.ts:
import { expect, test } from '@playwright/test'
test('shows the latest test runs with their status', async ({ page }) => {
await page.goto('/')
await expect(page.getByRole('heading', { name: 'TestRun Board' })).toBeVisible()
const table = page.getByRole('table', { name: 'Test runs' })
await expect(table.getByRole('row')).toHaveCount(8) // header + 7 runs
await expect(table.getByRole('row', { name: /login\.spec\.ts/ })).toContainText('flaky')
})
What makes it robust:
| Practice | In this test | Fragile alternative |
|---|---|---|
| Find elements as a user would | getByRole('table', { name: 'Test runs' }) | page.locator('div > div:nth-child(3) > table') |
| Wait by expecting, not by sleeping | await expect(...).toHaveCount(8) retries until true | await page.waitForTimeout(3000) |
| Check an outcome a user cares about | Seven runs, and login is flaky | “The page loaded” |
| One flow, one test | Only the overview | Filtering, sorting and details in one long test |
Judge the recording
Recorded and AI-generated tests often have the fragile column. Review your draft against the table, and ask the AI to fix specific problems: “Replace the CSS selectors with getByRole locators and remove all waitForTimeout calls.”
Then prove it works, as always: change the fixture in tests/mocks/data.ts so login is passed instead of flaky, run npm run e2e, and watch the test fail. Restore with git restore.
Exercise
- Run the existing UI test:
npx playwright install chromium(once), thennpm run e2e. - Record a test with
codegenthat filters the table to show only failed runs. Review it against the table above and improve it. - Break the app (or the data) so your test must fail, check that it does, and restore.
Key Takeaways
- Few UI tests, for the flows that matter most.
- Recording and AI give you a draft; you make it robust.
- Find elements by role and name, and wait with
expect, never with sleeps. - Prove the UI test fails when the behaviour is wrong.
