Playwright Tutorial for Beginners: Your First Test in TypeScript
Install Playwright, write your first TypeScript test, use reliable locators, debug with UI mode and organise tests with page objects.
Playwright has become one of the fastest-growing skills in Indian QA job descriptions, especially at product companies and startups that build modern web apps. If you already know manual testing or a little Selenium, Playwright is a very approachable next step: setup takes minutes, waits are built in, and the same test runs on Chromium, Firefox and WebKit.
This Playwright tutorial for beginners uses TypeScript and walks you from installation to a small, well-structured test suite. Every example runs against the official practice app at demo.playwright.dev, so you can follow along on your own laptop.
Key takeaways
- One command (
npm init playwright@latest) installs Playwright, browsers, a config file and a sample test. - Use user-facing locators such as
getByRole,getByLabelandgetByTextinstead of long CSS or XPath strings. - Playwright waits automatically before actions and inside
expectassertions, so you rarely need manual waits. - UI mode, Codegen and the Trace Viewer make writing and debugging tests much faster than in older tools.
- Page objects and fixtures keep a growing suite readable.
What is Playwright?
Playwright is an open-source end-to-end testing framework maintained by Microsoft. It drives real browsers (Chromium, Firefox and WebKit, the engine behind Safari) through a single API, and it ships with its own test runner called Playwright Test. You can write tests in TypeScript/JavaScript, Python, Java or .NET; TypeScript is the most common choice and gets new features first.
Compared with older tools, three things stand out for beginners:
- Auto-waiting: before clicking or typing, Playwright checks that the element is attached, visible, stable and enabled.
- Isolation: every test gets a fresh browser context, which behaves like a new incognito profile, so tests do not leak cookies or storage into each other.
- Tooling: recording, step-by-step debugging and full traces come in the box.
If you are still deciding between tools, read our detailed Playwright vs Selenium comparison first.
Step 1: Install Playwright
You need a current LTS version of Node.js and a code editor; VS Code with the official Playwright extension is the most convenient setup. Create an empty folder, open a terminal in it and run:
npm init playwright@latestThe installer asks a few questions. For this tutorial choose TypeScript, keep the tests folder as tests, say yes to a GitHub Actions workflow if you want CI later, and let it install the browsers. When it finishes you will see:
| File or folder | Purpose |
|---|---|
| playwright.config.ts | Browsers, base URL, retries, reporters and trace settings |
| tests/ | Your test files (*.spec.ts) |
| tests-examples/ | A larger sample suite to read later |
| package.json | Project dependencies, including @playwright/test |
Run the sample test to confirm everything works:
npx playwright test
npx playwright show-reportThe first command runs the tests headlessly in all configured browsers; the second opens the HTML report.
Step 2: Write your first test
Create tests/todo.spec.ts and add this test. It opens the TodoMVC demo, adds an item and checks that it appears.
import { test, expect } from '@playwright/test';
test('user can add a todo item', async ({ page }) => {
await page.goto('https://demo.playwright.dev/todomvc');
const newTodo = page.getByPlaceholder('What needs to be done?');
await newTodo.fill('Prepare for QA interview');
await newTodo.press('Enter');
await expect(page.getByTestId('todo-title')).toHaveText(['Prepare for QA interview']);
await expect(page.getByText('1 item left')).toBeVisible();
});A few things to notice:
- The
pageobject is a fixture. Playwright creates it for every test and closes it afterwards, so there is no setup or teardown code. - Every browser action returns a promise, which is why each line starts with
await. Forgettingawaitis the most common beginner bug. expect(locator)assertions retry until they pass or time out (5 seconds by default), which removes most timing problems.
Run only this file in headed mode so you can watch the browser:
npx playwright test tests/todo.spec.ts --headed --project=chromiumStep 3: Use the right locators
Locators tell Playwright which element to work with. The recommended approach is to locate elements the way a user or assistive technology sees them, which also makes tests survive CSS refactors.
| Locator | Example | Best for |
|---|---|---|
| getByRole | page.getByRole('button', { name: 'Sign in' }) | Buttons, links, headings, checkboxes |
| getByLabel | page.getByLabel('Email') | Form fields with labels |
| getByPlaceholder | page.getByPlaceholder('Search jobs') | Inputs without labels |
| getByText | page.getByText('1 item left') | Static text and messages |
| getByTestId | page.getByTestId('todo-title') | Elements with a data-testid attribute |
| locator (CSS) | page.locator('.job-card') | Fallback when nothing above fits |
Locators are lazy and strict. Lazy means Playwright finds the element only when you act on it. Strict means an action fails if the locator matches more than one element, which protects you from clicking the wrong row. Narrow a match with chaining and filters:
const row = page.getByRole('listitem').filter({ hasText: 'Prepare for QA interview' });
await row.getByRole('checkbox').check();
await expect(row).toHaveClass(/completed/);Step 4: Record tests with Codegen and debug in UI mode
You do not have to type every locator by hand. Codegen opens a browser, records your clicks and generates code with good locators:
npx playwright codegen https://demo.playwright.dev/todomvcTreat generated code as a first draft: rename things, remove extra steps and add meaningful assertions.
For daily work, UI mode is the best way to run and debug tests. It shows a watch mode, a timeline of every action and a DOM snapshot for each step:
npx playwright test --uiWhen a test fails in CI, the Trace Viewer lets you replay it step by step with network calls, console logs and screenshots. The default config records a trace on the first retry; open it from the HTML report or with npx playwright show-trace and the trace file path.
Step 5: Configure browsers, base URL and retries
Open playwright.config.ts. The settings beginners change most often are:
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
retries: process.env.CI ? 2 : 0,
reporter: 'html',
use: {
baseURL: 'https://demo.playwright.dev',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'mobile-chrome', use: { ...devices['Pixel 7'] } },
],
});With baseURL set, tests can call page.goto('/todomvc'). Projects let one test run in several browsers or device profiles without code changes, and tests run in parallel by default.
Step 6: Organise tests with hooks and page objects
As the suite grows, repeated navigation and locators become hard to maintain. Start with test.beforeEach for shared setup, then move page details into a page object class.
// pages/TodoPage.ts
import { Page, Locator } from '@playwright/test';
export class TodoPage {
readonly newTodo: Locator;
readonly items: Locator;
constructor(private readonly page: Page) {
this.newTodo = page.getByPlaceholder('What needs to be done?');
this.items = page.getByTestId('todo-title');
}
async open() {
await this.page.goto('/todomvc');
}
async add(text: string) {
await this.newTodo.fill(text);
await this.newTodo.press('Enter');
}
}// tests/todo-pom.spec.ts
import { test, expect } from '@playwright/test';
import { TodoPage } from '../pages/TodoPage';
test.describe('Todo list', () => {
let todo: TodoPage;
test.beforeEach(async ({ page }) => {
todo = new TodoPage(page);
await todo.open();
});
test('adds two items', async () => {
await todo.add('Learn locators');
await todo.add('Learn fixtures');
await expect(todo.items).toHaveCount(2);
});
});The test now reads like a test case, and if the placeholder text changes you fix it in one place. Later you can expose page objects as custom fixtures with test.extend, which is how many company frameworks are built.
Common beginner mistakes
- Missing
awaitbefore actions or assertions, which causes random failures. - Using
page.waitForTimeout()as a fix for timing issues instead of web-first assertions. - Copying long CSS chains from DevTools when a role or label locator exists.
- Making tests depend on each other’s data; each test should create what it needs.
- Asserting nothing. A test that only clicks through pages does not prove much.
What to learn next
Once you are comfortable with the basics, move on in this order:
- Authentication: log in once and reuse the saved storage state across tests.
- API testing with the built-in
requestfixture, useful for creating test data quickly. - Network mocking with
page.route()to test error states. - Running tests in CI with GitHub Actions and publishing the HTML report.
- Visual comparisons with
toHaveScreenshot().
For deeper coverage, see our Playwright handbook and the official Playwright documentation. When you start applying, practise with our Playwright interview questions.
🚀 Looking for Playwright automation jobs?
QA Jobs India shares 100+ fresh QA & software testing openings every morning — manual, automation, API and remote roles.
See today’s QA jobs →FAQs
Is Playwright good for beginners?
Yes. Installation is a single command, waits are automatic and UI mode shows exactly what happened at every step. Basic JavaScript or TypeScript knowledge (variables, functions, async/await) is enough to start.
Should I learn Playwright with TypeScript or Python?
TypeScript is the most widely used option and new features arrive there first, so it is the safer choice for job hunting. Python is a good option if your team or target company already uses it.
Do I need to learn Selenium before Playwright?
No. You can start directly with Playwright. Many Indian service companies still use Selenium, though, so learning its basics later through our Selenium WebDriver tutorial widens your options.
Is Playwright free?
Yes. Playwright is open source under the Apache 2.0 licence and free for commercial use.
How long does it take to learn Playwright?
With one to two hours of practice a day, most testers can write useful tests in two weeks and build a small framework with page objects, fixtures and CI in about a month.
Conclusion
You have installed Playwright, written and debugged your first tests, used reliable locators, configured multiple browsers and organised the suite with page objects. Push this project to GitHub, add a few more scenarios from a real website and you will have a portfolio project to discuss in interviews. Then keep checking the latest QA openings and apply with confidence.
- 100+ fresh QA jobs daily + Direct HR email IDsLive every morning at 9 AM — apply straight to HR
- Weekly Mega Job Fair800+ QA jobs from India & around the world, every week
- Certified QA coursesUp to 17 courses, with certificate
- AI ATS Resume BuilderFree resume points included
- Full LinkedQA feedEvery post, fully unblurred
- Complete QA Material libraryInterview Q&A, cheat sheets, templates & roadmaps
Instant activation right after payment · One login for jobs, courses, resume & LinkedQA
💎 Get every QA opening, every day
Join QA Jobs India Premium for 100+ verified QA jobs daily with HR contact details.