Skip to content

Playwright Explained in Simple Words

A plain-English guide built from the two Playwright cheat sheets. Read top to bottom once, then use it to revise before interviews.

One-line idea: Playwright is a tool that opens a real browser, clicks around like a human, and checks that your website works β€” automatically.


1. The Basics

What is Playwright?

An open-source tool from Microsoft for testing websites end-to-end (start to finish, like a real user). It can drive Chromium (Chrome/Edge), Firefox, and WebKit (Safari) with the same code.

Why people like it: - Works across all major browsers. - Runs many tests at the same time (parallel) β†’ faster. - Auto-waits for things to be ready β†’ fewer flaky/random failures. - Built-in screenshots, videos, and tracing to help you debug.

What languages can I use?

JavaScript / TypeScript, Python, .NET (C#), and Java. (TypeScript is the most common.)

Playwright vs Selenium (a classic interview question)

Selenium Playwright
Needs a separate WebDriver No WebDriver, talks to the browser directly
You add your own waits Auto-waiting built in
Slower to set up Faster, modern
Tracing/video are add-ons Tracing, video, screenshots built in

2. How It's Built (Architecture)

Playwright uses a client–server design: - Your test code = the client. - It talks to the browser = the server over a fast connection (WebSocket).

Because of this, each browser runs as its own process β†’ more stable and isolated.

Three key objects to remember: - Browser – the whole browser app you launched. - BrowserContext – an isolated "incognito-like" session inside that browser. Its own cookies, storage, and permissions. You can run several at once (e.g. two logged-in users). - Page – a single tab inside a context.

Think of it as: Browser β†’ Context (a fresh profile) β†’ Page (a tab).


3. Finding Things on the Page (Locators)

A locator is how you point at an element (a button, input, link) so you can act on it.

Playwright recommends user-facing locators (how a human sees the element) over fragile CSS/XPath: - getByRole – by its role (button, checkbox, heading). - getByText – by the text shown. - getByLabel – form fields by their label. - getByPlaceholderText – inputs by placeholder. - locator() – still supports CSS or XPath when needed.

Best practice: prefer stable locators (role, text, test-id) over brittle selectors.


4. Doing Things (Actions)

Actions are what you do to elements: - click, fill (type text), check / uncheck, selectOption (dropdowns). - hover, dblclick (double click), drag & drop. - Keyboard and mouse actions. - File upload, download. - Navigation: goto, goBack, goForward, reload.


5. Waiting (the part that kills flaky tests)

Auto-waiting

Before every action, Playwright automatically waits until the element is ready (visible, stable, and can receive events). Default timeout ~30 seconds, configurable. This is why Playwright tests are less flaky than older tools.

Explicit waits (when auto-wait isn't enough)

Sometimes you must wait for a specific condition: - waitForSelector – wait for an element to appear. - waitForLoadState – wait for the page to finish loading. - waitForFunction – wait until a piece of JS returns true. - waitForResponse – wait for a network call to finish.

Rule of thumb: rely on auto-wait first; add explicit waits only for special cases.


6. Checking Results (Assertions)

Assertions verify that things are as expected. Playwright's assertions auto-retry until true or timeout β€” again, less flakiness.

Common ones: - toBeVisible, toHaveText, toContainText - toHaveValue, toBeChecked, toHaveCount


7. Handling Tricky Page Elements

Situation What to do
iFrames (a page inside a page) Use frameLocator() or frame(), then act inside it
Multiple tabs / pop-ups Catch the new page with waitForEvent('page') (or 'popup'), then switch to it
Alerts / confirms / prompts (browser dialogs) Listen with page.on('dialog', ...) then dialog.accept() or dialog.dismiss(); read text with dialog.message()
File upload setInputFiles() on the <input type="file">
File download waitForEvent('download'), then download.saveAs(path)
Scrolling scrollIntoViewIfNeeded() or mouse.wheel()
Drag & drop dragTo(target)

8. Network & API

Network interception

You can watch and control the requests a page makes with route(): - Modify, mock, or block requests. - Great for faking API responses or blocking third-party junk (ads, trackers).

API testing

Playwright can also test your backend APIs directly (no browser needed): - Methods: GET, POST, PUT, DELETE, PATCH. - Validate status codes, headers, and response body. - Useful for contract/API tests.

Capturing responses

Use waitForResponse() or page.on('response', ...) to grab what the server sent back.


9. Login & Sessions (Storage State)

Logging in for every test is slow. Instead: - Storage state = saved cookies + localStorage + sessionStorage. - Log in once, save it with saveStorageState() / context.storageState(). - Reuse it in other tests β†’ much faster, more stable. - Supports form login, tokens, OAuth/SSO.

You can also manage cookies directly with context.addCookies() / context.cookies().


10. Organizing Tests

Page Object Model (POM)

A design pattern: make one class per page, holding that page's locators and actions. - Keeps tests clean and readable. - Reuse the same methods everywhere. - Easy to maintain big projects (change a locator in one place).

Fixtures

Reusable setup/precondition blocks. Built-in ones: page, context, browser. You can write custom fixtures for shared setup β†’ less repeated code.

Hooks

Code that runs before/after tests: - beforeAll / afterAll – once for the whole file. - beforeEach / afterEach – before/after every test. - Used for setup, teardown, logging, cleaning the database.


11. Configuration & Running

Config file (playwright.config.ts)

One place to control test behavior: - Timeouts, retries, reporters. - Which browsers/projects to run. - Base URL and global setup.

Parallel execution

Tests run in parallel by default using multiple "workers" β†’ faster, better for CI.

Retries

Set retries in the config so failed tests re-run automatically (helps with occasional flakiness).

Cross-browser testing

Configure Chromium, Firefox, and WebKit as "projects" so the same tests run on all of them.

Environment variables

Store environment-specific data (base URL, credentials, tokens) in .env files and read via process.env β€” keeps secrets out of the code and lets you switch environments.


12. Debugging & Reports

Tool What it does
Trace / Trace Viewer Records a detailed step-by-step timeline; open it to replay what happened. Set trace: 'on' or 'retain-on-failure' in config.
Screenshots screenshot(); auto-capture on failure with 'only-on-failure'
Video Record the whole run; 'retain-on-failure' keeps only failed ones
page.pause() Stops the test and opens the Inspector so you can step through
PWDEBUG=1 Environment variable to launch debug mode
Headed mode / slowMo Watch the browser with a visible UI, slowed down

Headless vs Headed

  • Headless = no visible browser window. Faster, used in CI pipelines.
  • Headed = you see the browser. Better for watching/debugging.

Visual testing

Compare a screenshot against a saved "baseline" with toHaveScreenshot() to catch UI changes.


13. Best Practices (say these in interviews)

  • Use locators, not raw selectors (prefer role/text/test-id).
  • Keep tests independent and isolated (no test depends on another).
  • Follow the Page Object Model.
  • Use meaningful assertions.
  • Lean on auto-waiting; avoid fixed sleeps.
  • Use fixtures for setup/teardown.
  • Capture traces, screenshots, videos for debugging.
  • Keep test data separate and clean.
  • Integrate with CI/CD; review and refactor tests regularly.

14. Common Interview Topics (quick checklist)

  • Playwright vs Selenium
  • Auto-waiting, Locators, Assertions
  • Hooks, Fixtures, Page Object Model
  • Network interception & API testing
  • Parallel execution
  • Storage state / authentication reuse
  • Tracing, screenshots, video, debugging
  • Handling frames, tabs, dialogs, uploads/downloads

30-second summary

Playwright opens real browsers and acts like a user. It auto-waits so tests are reliable, uses user-friendly locators, can mock networks and test APIs, saves login sessions for speed, and gives you traces/videos/screenshots to debug. Organize with the Page Object Model, run everything in parallel across browsers, and you have fast, stable, cross-browser tests.