This Playwright tutorial for beginners takes you from an empty folder to a small, working test suite: you install Playwright, write your first TypeScript test, pick locators that survive redesigns, mock an API call, debug a failure with a trace and run everything in CI. Every example targets a public demo app, so you can follow along on your own laptop without any accounts or paid tools.
If you later want structured practice with an instructor, our live Playwright training course builds on exactly these foundations. For now, all you need is Node.js and about an hour.
Quick answer: To start with Playwright, install Node.js 22 or newer, run npm init playwright@latest in a new folder, and accept the TypeScript defaults. Write tests in the tests folder using page.getByRole() locators and expect() assertions, run them with npx playwright test, and open the report with npx playwright show-report.
Key takeaways
- Playwright Test is a free, open source end-to-end testing framework from Microsoft that drives Chromium, Firefox and WebKit through one API.
- A single command,
npm init playwright@latest, creates the config file, an example test and (optionally) a GitHub Actions workflow. - Prefer user-facing locators such as
getByRoleandgetByLabel; they make tests easier to read and harder to break. - Actions wait for elements automatically and web-first assertions retry, so you rarely need manual waits.
- UI mode, Codegen and the trace viewer are built in, which makes debugging much faster than reading logs alone.
What is Playwright?
Playwright is a browser automation library with an official test runner called Playwright Test. The official documentation describes it as an end-to-end framework that bundles the runner, assertions, test isolation, parallel execution and tooling in one package. It is released under the Apache 2.0 license and maintained by Microsoft on GitHub.
Three ideas make Playwright feel different from older tools, and they are worth understanding before you write a line of code:
- Cross-browser by default. The same test runs on Chromium, Firefox and WebKit, on Windows, Linux or macOS, headless or with a visible window. Mobile viewports for Chrome on Android and Mobile Safari can be emulated.
- Auto-waiting. Before a click or a fill, Playwright checks that the element is actionable (visible, stable, enabled and so on). You do not sprinkle sleeps through your code.
- Isolation. Each test gets a fresh browser context, which behaves like a brand new browser profile. Cookies or local storage from one test never leak into the next.
Playwright also has official libraries for Python, Java and .NET. This tutorial uses TypeScript because the Node.js package ships with the full Playwright Test runner, reporters and UI mode, which is the smoothest path for a beginner.
Playwright tutorial for beginners: what you need first
- Node.js 22, 24 or 26. These are the versions listed in the current system requirements. Run
node --versionto check yours. - A supported operating system: Windows 11 or WSL, macOS 14 (Sonoma) or later, or Debian 12/13 and Ubuntu 22.04, 24.04 or 26.04.
- An editor. VS Code is a good choice because the official Playwright extension lets you run and debug tests from the sidebar.
- Basic JavaScript. You should be comfortable with functions and
async/await. Everything else is explained below.
Step 1: Install Playwright
Create an empty folder, open a terminal in it and run the init command:
mkdir playwright-starter
cd playwright-starter
npm init playwright@latest The installer asks four questions. For this tutorial, accept the defaults: TypeScript, a tests folder, yes to the GitHub Actions workflow and yes to installing the browsers. When it finishes, your folder contains:
playwright.config.ts: browsers (called projects), timeouts, retries and reporters.tests/example.spec.ts: a minimal example test.package.jsonwith@playwright/testas a dev dependency..github/workflows/playwright.ymlif you chose the CI workflow.
You can re-run the init command later without losing tests you have written. To upgrade an existing project, run npm install -D @playwright/test@latest followed by npx playwright install --with-deps so the browser binaries match.
Step 2: Run the example test and open the report
Run the whole suite:
npx playwright test By default the tests run headless and in parallel on all three browser engines, and the results appear in the terminal. A few flags you will use every day:
npx playwright test --headed # watch the browser
npx playwright test --project=chromium # one browser only
npx playwright test tests/todo.spec.ts # one file
npx playwright test --ui # interactive UI mode
npx playwright show-report # open the HTML report The HTML report opens automatically only when something fails. It lets you filter by browser and by passed, failed, flaky or skipped tests, and each test shows its steps, errors and attachments.
Step 3: Write your first Playwright test
Playwright hosts a TodoMVC demo app at demo.playwright.dev/todomvc, which is perfect for practice. Create tests/todo.spec.ts with this test. It adds two items, completes one and checks the counter:
import { test, expect } from '@playwright/test';
test('completing a todo updates the counter', async ({ page }) => {
await page.goto('https://demo.playwright.dev/todomvc/');
const newTodo = page.getByPlaceholder('What needs to be done?');
await newTodo.fill('Renew library books');
await newTodo.press('Enter');
await newTodo.fill('Plan weekend hike');
await newTodo.press('Enter');
// Both items are listed, in order
await expect(page.getByTestId('todo-title')).toHaveText([
'Renew library books',
'Plan weekend hike',
]);
await expect(page.getByTestId('todo-count')).toHaveText('2 items left');
// Complete the first item
await page.getByRole('checkbox', { name: 'Toggle Todo' }).first().check();
await expect(page.getByTestId('todo-count')).toHaveText('1 item left');
}); Run it with npx playwright test tests/todo.spec.ts --project=chromium --headed. Notice what is missing: there are no waits. Each action waits until the element is ready, and each expect keeps retrying until the text matches or the timeout expires.
The page argument is a fixture. Playwright creates it for every test inside an isolated browser context and closes it afterward, so you never manage browser startup or cleanup yourself.
Step 4: Choose locators that survive redesigns
A locator is a recipe for finding an element at the moment you act on it. Because Playwright resolves the locator again before every action, a re-rendered element is not a problem. What matters is choosing a recipe that matches how users see the page. The documentation recommends this order:
| Locator | Finds an element by | Good for |
|---|---|---|
getByRole() | ARIA role and accessible name | Buttons, links, checkboxes, headings |
getByLabel() | Associated label text | Form fields |
getByPlaceholder() | Placeholder text | Inputs without a label |
getByText() | Visible text content | Non-interactive text |
getByAltText() / getByTitle() | Alt text or title attribute | Images and icons |
getByTestId() | A data-testid attribute | Elements with no stable user-facing text |
CSS and XPath selectors still work, but they tie your test to the page structure. A class name change from a design refresh can break dozens of tests, while a button called “Sign in” usually stays “Sign in”.
Locators can be chained and filtered. For example, page.getByTestId('todo-item').filter({ hasText: 'Plan weekend hike' }) narrows a list down to one row before you act on it.
Step 5: Make assertions that wait
Playwright has two kinds of assertions, and mixing them up is a classic beginner mistake:
- Web-first (async) assertions such as
toBeVisible(),toHaveText(),toHaveValue(),toHaveCount(),toHaveURL()andtoHaveTitle(). They take a locator or page, are awaited, and retry until the condition is met. - Generic matchers such as
toEqual(),toContain()andtoBeTruthy(). They check a value you already have, run once and are not awaited.
If you read text with await locator.textContent() and then compare it with toEqual, you lose the retry and invite flaky failures. Pass the locator to a web-first assertion instead.
Step 6: Organize tests with hooks and a page object
Once you have more than a handful of tests, two patterns keep the suite tidy. Hooks remove repeated setup, and a page object puts locators and actions for one screen in one place.
// tests/pages/todo-page.ts
import { type Page, type Locator, expect } from '@playwright/test';
export class TodoPage {
readonly newTodo: Locator;
readonly titles: Locator;
readonly counter: Locator;
constructor(private readonly page: Page) {
// Assign locators in the constructor, not in field initializers
this.newTodo = page.getByPlaceholder('What needs to be done?');
this.titles = page.getByTestId('todo-title');
this.counter = page.getByTestId('todo-count');
}
async open() {
await this.page.goto('https://demo.playwright.dev/todomvc/');
}
async add(...items: string[]) {
for (const item of items) {
await this.newTodo.fill(item);
await this.newTodo.press('Enter');
}
}
async expectRemaining(text: string) {
await expect(this.counter).toHaveText(text);
}
} // tests/todo-pom.spec.ts
import { test, expect } from '@playwright/test';
import { TodoPage } from './pages/todo-page';
test.describe('todo list', () => {
let todo: TodoPage;
test.beforeEach(async ({ page }) => {
todo = new TodoPage(page);
await todo.open();
});
test('shows every added item', async () => {
await todo.add('Water the plants', 'Call the dentist', 'Back up laptop');
await expect(todo.titles).toHaveCount(3);
await todo.expectRemaining('3 items left');
});
}); Why assign locators in the constructor? Playwright 1.65 changed how TypeScript class fields are compiled to follow the useDefineForClassFields setting, and a field initializer that reads a constructor parameter property such as this.page now fails because the initializer runs first. Many older page object examples online use that pattern, so this is a good habit to adopt from day one.
Step 7: Mock an API response
Real end-to-end tests are valuable, but sometimes a backend is slow, unstable or hard to put into a specific state. Playwright can intercept any request the page makes with page.route() and answer it with your own data. Playwright hosts a small demo page that loads a list of fruits from an API, which makes it easy to try:
import { test, expect } from '@playwright/test';
test('renders fruits returned by a mocked API', async ({ page }) => {
// Register the route BEFORE navigating
await page.route('*/**/api/v1/fruits', async (route) => {
await route.fulfill({
json: [
{ name: 'Dragon fruit', id: 501 },
{ name: 'Persimmon', id: 502 },
],
});
});
await page.goto('https://demo.playwright.dev/api-mocking');
await expect(page.getByText('Dragon fruit')).toBeVisible();
await expect(page.getByText('Persimmon')).toBeVisible();
}); The real API is never called. You can also let the request through, read the response with route.fetch() and patch it, or replay many recorded requests from a HAR file. For testing an API directly without a browser, the built-in request fixture (an APIRequestContext) sends HTTP calls from Node.js, which is handy for creating test data before a UI test runs.
Step 8: Generate, explore and debug tests
Three built-in tools save beginners a lot of time:
Codegen
Run npx playwright codegen demo.playwright.dev/todomvc. A browser opens next to the Playwright Inspector, and every click or keystroke becomes code. Codegen prefers role, text and test id locators, and its Pick Locator button shows the locator for any element you hover. Treat the output as a first draft: rename things, remove redundant steps and add meaningful assertions.
UI mode
npx playwright test --ui opens a window where you can run single tests, watch files for changes and step backward and forward through each action.
Trace viewer
The generated config records a trace on the first retry of a failed test, and retries are set to 2 on CI and 0 locally. A trace is a zip file with DOM snapshots, network calls, console logs and source for every step. Open it from the HTML report, or force tracing on a local run with npx playwright test --trace on. When a test fails only in CI, the trace usually tells you why within minutes.
Step 9: Run your tests in CI
If you accepted the GitHub Actions option during setup, the playwright.yml workflow already runs your suite on every push and pull request to the main branch. It checks out the code, installs Node.js and dependencies, installs the browsers with system dependencies, runs npx playwright test and uploads the HTML report as a build artifact.
Push the project to a GitHub repository and open the Actions tab to watch the run. When a test fails, download the playwright-report artifact and open it with npx playwright show-report followed by the extracted folder name. The documentation also recommends setting globalTimeout in the config so a stuck run still produces a report. Other CI systems such as Azure Pipelines, GitLab CI and Jenkins work the same way; if your team uses them, our Azure DevOps course covers pipeline basics.
Playwright vs Selenium: which should a beginner learn?
This is the question most new automation testers ask. Both are open source and worth knowing:
| Aspect | Playwright | Selenium |
|---|---|---|
| Languages | JavaScript/TypeScript, Python, Java, .NET | Java, Python, C#, Ruby, JavaScript, Kotlin |
| Browser control | Downloads its own Chromium, Firefox and WebKit builds and controls them directly | W3C WebDriver standard across all major browsers |
| Waiting | Auto-waiting actions and retrying assertions | Explicit waits written by the tester |
| Test runner | Playwright Test is included (JS/TS); Pytest plugin for Python | Use JUnit, TestNG, pytest or another runner |
| Debugging tools | Codegen, UI mode, trace viewer, HTML report built in | Selenium IDE for record and playback; reports come from your runner |
| Scaling | Parallel workers and sharding in the runner | Selenium Grid distributes tests across machines |
For a new web project, Playwright is usually quicker to get productive with because so much comes in the box. Selenium remains widely used in large existing suites and teams that rely on the WebDriver standard, so many job descriptions still ask for it. If you are aiming at QA roles in enterprises, learning both is a smart move; our Selenium training course covers the WebDriver side.
Using AI with Playwright: Test Agents and MCP
Recent Playwright versions ship three Test Agents: a planner that explores your app and writes a Markdown test plan, a generator that turns the plan into test files while checking locators live, and a healer that runs the suite and tries to repair failing tests. You add their definitions to a project with npx playwright init-agents plus a flag for your AI tool, and you should regenerate them after each Playwright upgrade.
Separately, Playwright MCP lets AI assistants drive a real browser through the Model Context Protocol. If MCP is new to you, read our guide to the Model Context Protocol first. Either way, learn to write tests by hand before you lean on agents: you need to recognize a weak locator or a missing assertion to judge what an agent produces.
Common beginner mistakes to avoid
- Adding fixed waits.
page.waitForTimeout()slows every run and still fails on a slow day. Use web-first assertions instead. - Copying long CSS selectors from DevTools. Start with
getByRoleand only fall back to CSS when nothing user-facing exists. - Sharing state between tests. Each test should set up what it needs. For logins, save the authenticated storage state once in a setup project and reuse it.
- Forgetting
await. A missingawaitbefore an action or web-first assertion leads to confusing, intermittent failures.
Automation skills also strengthen your wider engineering profile. If you are building toward DevOps work, our Terraform tutorial for beginners and the article on applying machine learning to DevOps are good next reads, and you can browse every program on our courses page.
Learn Playwright with live, instructor-led training
Our Playwright course takes you from these basics to a maintainable TypeScript framework with page objects, API mocking, CI pipelines and AI-assisted testing, all in hands-on labs. Classes run live online, so you can join from the US, the UK or anywhere else, and you can start with a free demo.
Frequently asked questions
Is Playwright easy to learn for beginners?
Yes, for anyone with basic JavaScript. The installer sets up a working project in one command, auto-waiting removes the most common source of flaky tests, and Codegen shows you working code for any interaction.
Should I learn Playwright with JavaScript, TypeScript or Python?
Choose the language your team or target employers use. If you have no preference, TypeScript is a strong default because the Node.js package includes the full Playwright Test runner, UI mode and reporters, and type hints catch mistakes early. Python users get a supported Pytest plugin.
Is Playwright better than Selenium?
Neither is better in every case. Playwright offers more built-in tooling and automatic waiting, which suits new web projects. Selenium follows the W3C WebDriver standard, supports more languages and has a long track record in large enterprise suites.
Is Playwright free to use?
Yes. Playwright, including the Playwright Test runner, is open source under the Apache 2.0 license, which allows use in commercial projects. You do not need a paid plan or account to write and run tests locally or in CI.
Can Playwright be used for API testing?
Yes. The request fixture sends HTTP requests directly from Node.js through APIRequestContext, so you can test REST endpoints on their own or use API calls to prepare and verify data around your UI tests.
Sources
- Playwright documentation: Installation, Writing tests, Locators, Generating tests, Trace viewer, Mock APIs, API testing, Authentication, Setting up CI, Test Agents, Supported languages, Release notes
- Playwright license (Apache 2.0) on GitHub
- Selenium documentation