Playwright Tutorial for Beginners (TypeScript)
Playwright is an open-source framework from Microsoft for end-to-end testing of web apps in Chromium, Firefox, and WebKit. This tutorial takes you from installation to a running, debuggable TypeScript test in about 30 minutes.
Everything below was run on Playwright 1.65 and Node.js 22. Copy the commands as they are, and they will work. The official reference lives at playwright.dev, and every version number and default in this guide comes from there.
What Is Playwright and Why Teams Choose It
Playwright drives a real browser and checks what a real user would see. It is Apache-2.0 licensed, so it is free for commercial projects, and Microsoft ships a new minor version roughly once a month.
Five things make it a comfortable starting point:
- Three browser engines, one API. Chromium, Firefox and WebKit. WebKit is what powers Safari, so you get Safari-shaped coverage without a Mac in the loop.
- Auto-waiting. Before a click, Playwright checks that the element is visible, stable, enabled, not inert, and actually receiving events. You stop writing sleeps.
- Parallel runs. Test files run in parallel out of the box in separate worker processes, and every test gets a fresh browser context.
- Trace Viewer. When a test fails, you get a recording you can step through — DOM snapshot, network, console, per-action screenshots.
- Codegen. Click through your app and Playwright writes the first draft of the test for you.
A quick word on Selenium
Selenium is older, supports more languages, and has the larger ecosystem — if your team already writes Java, that matters. Playwright is newer, ships the runner, assertions, reporting and tracing in one package, and needs no separate WebDriver binary.
One thing to be clear about: this tutorial covers the tool, not the shape of the project around it. We will come back to that.
Prerequisites
You need three things:
- Node.js. Playwright’s docs recommend the latest 22.x, 24.x or 26.x release. The package itself requires Node 20 or newer. Check yours with node -v.
- VS Code (optional, but useful). The official Playwright extension gives you a test sidebar, run-on-click, and a pick-locator button.
- Basic TypeScript. You need to recognise async/await, arrow functions, and imports. You do not need generics, decorators or any type gymnastics. Playwright’s own examples stay simple on purpose.
If your team works mainly in Python, the same concepts apply through a different binding — our guide to Python for automation in 2026 covers that stack.
Optimize Your Testing Today
Ready to level up your quality? From test automation services to full-scale software testing outsourcing, we help you build a product that is extraordinary.
Step 1. Install Playwright
Make an empty folder, open a terminal in it, and run:
npm init playwright@latest
The installer asks four questions:
- “Do you want to use TypeScript or JavaScript?” — pick TypeScript, the default.
- “Where to put your end-to-end tests?” — tests is the default and works fine.
- “Add a GitHub Actions workflow?” — say yes. You will want it later.
- “Install Playwright browsers?” — say yes. This downloads Chromium, Firefox and WebKit.
On Linux you may also get a fifth question about installing operating system dependencies, which needs sudo.
The download is substantial — several hundred megabytes per browser engine — so give it a few minutes. When it finishes, your folder looks like this:
.
├── .github/
│ └── workflows/
│ └── playwright.yml ← CI pipeline, ready to run
├── tests/
│ └── example.spec.ts ← a working example test
├── .gitignore
├── package.json
├── package-lock.json
└── playwright.config.ts ← browsers, retries, reporters, tracing
Two files matter.
playwright.config.ts is the control panel. It sets which browsers run (projects), how many retries, which reporter, and when to record traces. All three engines — Chromium, Firefox and WebKit — are active from the start. Mobile viewports and branded browsers like Edge are in the file too, commented out and ready when you want them.
tests/example.spec.ts is a real test against playwright.dev. Run it now to confirm the install worked:
npx playwright test
6 tests pass — two tests across three browsers. That multiplication surprises people: a suite of 40 tests is 120 runs. Step 5 shows how to narrow it while you are writing.
Step 2. Write Your First Test
Here is the test the installer generates. It is short, and every line does something worth understanding:
import { test, expect } from ‘@playwright/test’;
test(‘has title’, async ({ page }) => {
await page.goto(‘https://playwright.dev/’);
// Expect a title “to contain” a substring.
await expect(page).toHaveTitle(/Playwright/);
});
test(‘get started link’, async ({ page }) => {
await page.goto(‘https://playwright.dev/’);
// Click the get started link.
await page.getByRole(‘link’, { name: ‘Get started’ }).click();
// Expects page to have a heading with the name of Installation.
await expect(page.getByRole(‘heading’, { name: ‘Installation’ })).toBeVisible();
});
Line by line:
- import { test, expect } — the test runner and the assertion library both come from @playwright/test. No Mocha, no Jest, no Chai to wire up.
- test(‘has title’, async ({ page }) => { — the name is what shows up in reports, so write it as a sentence a non-engineer could read. { page } is a fixture: Playwright hands each test a fresh page in a fresh browser context, so no test can leak state into another.
- await page.goto(…) — almost everything in Playwright is async. Forget an await and your test passes while doing nothing, which is the single most common beginner bug.
- await expect(page).toHaveTitle(/Playwright/) — a regex, so the assertion passes on any title containing “Playwright”.
- getByRole(‘link’, { name: ‘Get started’ }) — find the element the way a screen reader would: by its role and its accessible name.
Now write your own. Create tests/login.spec.ts and adapt this to your app:
import { test, expect } from ‘@playwright/test’;
test(‘a signed-in user lands on the dashboard’, async ({ page }) => {
await page.goto(‘/login’);
await expect(page).toHaveTitle(/Sign in/);
await page.getByLabel(‘Email’).fill(‘[email protected]’);
await page.getByLabel(‘Password’).fill(‘correct-horse’);
await page.getByRole(‘button’, { name: ‘Sign in’ }).click();
await expect(page).toHaveURL(/dashboard/);
await expect(page.getByRole(‘heading’, { name: ‘Dashboard’ })).toBeVisible();
});
The relative path works because of baseURL in the config. Set it once and your tests stop carrying environment details:
use: {
baseURL: ‘http://localhost:3000’,
trace: ‘on-first-retry’,
},
Now the same suite runs against local, staging or production by changing one line.
Step 3. Locators That Don’t Break
A locator is how Playwright finds an element. Pick badly and your suite breaks every time a developer touches the CSS. This is where most beginner test automation goes wrong.
Playwright gives you built-in locators in a deliberate order of preference:
| Locator | Use it for | Example |
|---|---|---|
getByRole() | Almost everything | getByRole('button', { name: 'Sign in' }) |
getByLabel() | Form fields | getByLabel('Email') |
getByPlaceholder() | Inputs with no label | getByPlaceholder('Search orders') |
getByText() | Static copy | getByText('Wrong email or password') |
getByTestId() | Anything with no accessible handle | getByTestId('order-total') |
Start with getByRole. It matches on the element’s role and its accessible name, which is close to what a user perceives. A button keeps working as a button whether it is styled blue or green, moved into a modal, or re-indented.
There is a side benefit. If you cannot find an element by role and name, that is often a real accessibility defect rather than a Playwright problem — a button with no accessible name is unusable for screen-reader users too.
Use getByTestId when markup gives you nothing. Add data-testid to the element and locate it by that. It is explicit, and developers can see at a glance that something depends on it. Playwright reads data-testid by default; change the attribute with testIdAttribute in your config.
Avoid long CSS and XPath chains. Playwright’s own docs call them a bad practice, and they are right:
// Brittle — breaks when anyone touches the layout
page.locator(‘div.container > div:nth-child(3) > form > button.btn-primary’);
// Resilient — survives a redesign
page.getByRole(‘button’, { name: ‘Sign in’ });
page.locator() still exists for the cases where you genuinely need a CSS or XPath selector. Keep them short and anchored to something stable, like an id.
Locators are half of a suite that survives a year. The other half is structure, which is the subject of how to set up a test automation framework.
Step 4. Assertions
Playwright’s assertions are web-first: they retry until they pass or the timeout expires, which is 5 seconds by default. You do not need to wait for the UI to settle before asserting.
The ones you will use constantly:
await expect(page.getByRole(‘heading’, { name: ‘Dashboard’ })).toBeVisible();
await expect(page.getByTestId(‘error-message’)).toHaveText(‘Wrong email or password’);
await expect(page).toHaveURL(/dashboard/);
await expect(page.getByTestId(‘cart-item’)).toHaveCount(3);
await expect(page.getByRole(‘button’, { name: ‘Pay’ })).toBeEnabled();
Note the await on every one. Web-first assertions are async because they retry. Miss the await and the assertion never actually runs.
Soft assertions
A normal failed assertion stops the test. Sometimes you want to check several things and see all the failures at once — a summary screen with five fields, for instance. Use expect.soft:
test(‘order summary shows the right values’, async ({ page }) => {
await page.goto(‘/dashboard’);
await expect.soft(page.getByTestId(‘order-total’)).toHaveText(‘49.90’);
await expect.soft(page.getByTestId(‘order-status’)).toHaveText(‘delivered’);
await expect(page.getByText(‘Sign out’)).toBeVisible();
});
A failing soft assertion marks the test as failed while allowing the rest of the test to run. One run tells you all three fields are wrong instead of just the first.
Use them for independent checks on one screen. Do not use them for anything the next step depends on — if the login failed, continuing into the dashboard just produces noise.
Step 5. Run Tests
The basics:
npx playwright test # everything, headless
npx playwright test tests/login.spec.ts # one file
npx playwright test –headed # watch the browser
npx playwright test –project=chromium # one browser instead of all three
npx playwright test –workers=3 # three parallel workers
npx playwright test –last-failed # only what failed last time
Headless by default. No browser window opens, which is faster and is what CI needs. Add –headed when you want to watch.
Narrow while you write. Running all three engines on every save gets slow. Stick to –project=chromium during development and let CI run the full matrix.
UI mode is where you should spend your time while writing tests:
npx playwright test –ui
It opens a window with your whole suite, a watch mode, a timeline of every action, and DOM snapshots you can inspect at any step. It is the fastest feedback loop Playwright offers, and most beginners find it long after they needed it.
Parallel runs come free. Test files run in parallel, each in its own worker. The generated config also sets fullyParallel: true, which parallelises tests within a file as well. Set the count with –workers, or –workers=1 to turn parallelism off while you debug a race.
Parallelism is also the reason tests must not share state. More on that below.
Step 6. Debug with Trace Viewer and Codegen
Trace Viewer
A trace is a recording of a test run: every action, a DOM snapshot before and after, network calls, console output, and the source line that triggered each step.
The generated config enables it on retry:
use: {
trace: ‘on-first-retry’,
},
Other values are ‘on’ (heavy, not recommended for every run), ‘off’, ‘on-all-retries’ and ‘retain-on-failure’. To force a trace for a single run:
npx playwright test –trace on
Open it with the path Playwright prints after a failure:
npx playwright show-trace test-results/login-a-signed-in-user-lan-chromium/trace.zip
You get a timeline. Click any action and you see the page as it was at that moment. For “it passes locally but fails in CI”, this is the tool — download the trace artifact from the pipeline and step through the exact failing run.
Codegen
npx playwright codegen demo.playwright.dev/todomvc
A browser opens alongside an inspector window. Click, type and navigate, and Playwright writes the test as you go — using getByRole and friends, not CSS chains.
Treat the output as a first draft. Codegen is excellent at finding the right locator and clumsy at structure: it produces one long test with no meaningful name and no assertions worth keeping. Take the locators, rewrite the rest.
Step 7. Reports
The generated config uses the HTML reporter. After a run:
npx playwright show-report
You get a browsable report at playwright-report/index.html with every test, its duration, and a full trace for the failures.
To capture evidence on failure, add two lines to use:
use: {
baseURL: ‘http://localhost:3000’,
trace: ‘on-first-retry’,
screenshot: ‘only-on-failure’,
video: ‘retain-on-failure’,
},
Now a failing test leaves a test-failed-1.png and a video.webm next to its trace, and all three are embedded in the HTML report. Videos are recorded for every test and deleted for the ones that pass, so the cost is bounded.
Once more than a couple of people read these results, a static HTML file stops being enough. You will want history, flaky-test tracking and a link between tests and requirements — that is what a test management tool for Playwright is for.
Common Beginner Mistakes
Hard waits. await page.waitForTimeout(3000) is the fastest way to build a slow, flaky suite. It is too short on a loaded CI runner and too long everywhere else. Playwright already waits for elements to be actionable and retries assertions, so let it. If you truly need to wait for a condition, wait for the condition: page.waitForURL(), page.waitForResponse(), or just an assertion.
Brittle selectors. Covered above, and worth repeating because it drives more maintenance cost than anything else in automated testing. A suite that breaks on every redesign gets switched off within two sprints.
Shared state between tests. Each test gets a fresh browser context, so cookies and storage start clean. The thing that bites teams is shared data — two tests editing the same user record, running in parallel, failing at random. Give each test its own data, or its own account.
Forgetting await. A test with a missing await usually passes, because the assertion never ran. Enable @typescript-eslint/no-floating-promises and the compiler catches these for you.
Testing everything through the UI. Logging in through the form in all 60 tests is 60 slow, fragile logins. Set up state through the API or a saved storage state, and keep the UI tests for the UI.
What to Learn Next
You have a running suite. These are the next four steps, roughly in order:
- Page Object Model. Move locators out of your tests and into classes that represent screens. Your tests start reading like user journeys instead of DOM queries.
- CI. The installer already wrote .github/workflows/playwright.yml. Enable it so every pull request runs the suite. One note: the generated workflow pins actions/checkout@v4 and actions/setup-node@v4, while both actions are on v7. Bump them before you rely on the pipeline.
- AI-assisted test writing. Playwright MCP lets an AI agent drive a real browser and write tests against what it actually sees.
- Accessibility. Add @axe-core/playwright, and you get automated WCAG checks inside the suite you already have. Start with our guide to axe-core and Playwright accessibility testing.
Ready to Scale Beyond Your First Test?
The first Playwright test is easy. A suite your team trusts at release time — stable locators, sensible test data, CI that catches real regressions instead of crying wolf — takes experience most teams build the slow way.
We can help you build it the fast way. Our test automation services cover framework setup, Playwright suite development, and CI integration, delivered by ISTQB-certified QA engineers who have done it before. If you need manual coverage alongside it, that sits in the same software testing services package — one team, one process.
Contact us to talk through what your product needs.
FAQs
For a first end-to-end suite on a JavaScript or TypeScript product, usually yes. Playwright ships the runner, assertions, reporting and tracing in one install, and auto-waiting removes the flakiness that drives beginners away. Selenium still wins on language coverage and real-device grids, so if your team writes Java, the calculation changes.
Yes. The installer asks, and JavaScript is a supported option. We still recommend TypeScript for a new project: type checking catches a missing await or a misspelled method before the test runs, and it costs nothing to adopt because Playwright ships its own types.
It supports mobile emulation, not real devices. Playwright simulates a device’s user agent, viewport, screen size and touch support, and the generated config includes ready-made profiles like devices[‘Pixel 5’] and devices[‘iPhone 12’].
That catches responsive layout bugs. It does not catch device-specific rendering, real network conditions, OS-level permission dialogs, or anything in a native app. For those you need real devices and an appropriate tool.
Yes. Playwright is open source under the Apache-2.0 licence, free for commercial use, with no paid tier and no per-seat cost. Your spend is the CI minutes you run it on.
You can have a working test in under an hour — that is what this tutorial is for. Being productive takes two to three weeks: writing stable locators, structuring a suite, handling authentication and test data, and reading traces when something fails.
Getting a suite that stays green for a year is a different skill. That is test design, not tool knowledge, and it is where most in-house efforts stall.