Playwright NotesRohit’s interview study guide
Chapter 01

What Playwright Is and How It Works

What Playwright is, how it drives a real browser, the browser → context → page model that makes tests isolated, the auto-waiting that removes sleeps, and how it compares with Cypress and Selenium. Every example was run with Playwright 1.65.1 against the Practice Shop.

6 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#What Playwright is

Added

Playwright is a tool that drives real browsers from code: it opens Chromium, Firefox or WebKit (Safari's engine), loads your app, clicks, types and reads the page exactly as a user would, and lets you check what happened. Microsoft released it in January 2020; it was started by the engineers who had built Puppeteer at Google, with the goal of one API for every modern browser engine instead of Chrome only.

It comes in two parts, and it helps to keep them apart in your head:

  • The library (playwright): launch a browser, open pages, click and read. You can use it in any Node script: scraping, generating PDFs, automating a form. It knows nothing about tests.
  • The test runner (@playwright/test): the part you use for testing. It finds your test files, gives each test a fresh browser page, runs tests in parallel, retries, takes screenshots and traces on failure, and reports the results. It includes the library.

The mental model: the library is a remote control for a browser; the test runner is a test lab built around that remote control, with clean rooms (a fresh page per test), a scheduler (workers running tests in parallel) and a lab notebook (the reports and traces). In interviews, "Playwright" almost always means the test runner.

Here's the library on its own: a plain Node script that opens the Practice Shop, signs in and prints what it sees. There's no test and no expect, just a browser being driven.

shop-title.mjs
import { chromium } from "playwright";

const browser = await chromium.launch();      // starts a real (headless) Chromium
const page = await browser.newPage();         // a new tab in a fresh, empty profile

await page.goto("https://rohit-playwright.pages.dev/practice/");
console.log("Title:", await page.title());

await page.getByLabel("Username").fill("rohit");
await page.getByLabel("Password").fill("playwright");
await page.getByRole("button", { name: "Sign in" }).click();

await page.waitForURL("**/practice/shop");    // signing in takes half a second
console.log("Now at:", new URL(page.url()).pathname);
console.log("Heading:", await page.getByRole("heading", { level: 1 }).textContent());

await browser.close();
node shop-title.mjs
Title: Sign in · Practice Shop
Now at: /practice/shop
Heading: Products
What’s happening
  1. chromium.launch() starts a real Chromium process (headless: no window) and returns a Browser. Nothing is shared with the Chrome you browse with: no cookies, no history, no extensions.
  2. browser.newPage() creates a fresh browser context (an empty profile, explained below) with one tab in it, so the shop sees a first-time visitor with nothing in localStorage.
  3. page.goto() loads the sign-in page and waits for its load event; page.title() reads the <title>, which is why the first line is "Sign in · Practice Shop".
  4. getByLabel("Username") finds the input by its visible label, the way a person would, and fill() types into it. getByRole("button", { name: "Sign in" }) finds the button by its role and text, and click() presses it.
  5. The shop takes 500 ms to sign in (it pretends to call a server), so the script waits for the URL to become /practice/shop instead of guessing a delay. Then it reads the page's main heading: "Products".
  6. browser.close() ends the browser process. Forget it and the script never exits, because the browser is still running.
AdvancedThe test runner wraps all of this

The test runner wraps all of this. You don't launch browsers or close them; each test asks for a page and gets a fresh one, and you check things with expect:

tests/sign-in.spec.ts
import { test, expect } from "@playwright/test";

test("rohit can sign in", async ({ page }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();

  await expect(page).toHaveURL("/practice/shop");
  await expect(page.getByRole("heading", { level: 1 })).toHaveText("Products");
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/sign-in.spec.ts:3:1 › rohit can sign in (962ms)

  1 passed (1.4s)
What’s happening
  1. test("…", async ({ page }) => …) declares a test. The { page } is a fixture: the runner launches the browser, makes a new context and page for this test, hands it over, and closes it afterwards. You never write launch() or close().
  2. page.goto("/practice/") is relative: the config's baseURL (https://rohit-playwright.pages.dev) is put in front. Chapter 2 shows the config.
  3. The three lines that sign in are the same as in the script.
  4. await expect(page).toHaveURL("/practice/shop") doesn't check once: it keeps checking until the URL matches or 5 seconds pass. That's why there's no waitForURL here: the assertion is the wait.
  5. The output is the runner's list reporter: one line per test with the browser project ([chromium]), the file and line, the test's title and how long it took, then a summary. A failing test would print ✘ and the reason.

#How Playwright talks to the browser

Added

When your test calls page.click(), the click doesn't happen inside your Node process. Your test code sends a command to the browser, and the browser does the work. How that command travels is the main thing that separates the tools.

Playwright keeps one open connection per browser (a pipe to a browser it launched, or a WebSocket to a remote one) and sends small messages over it in both directions. For Chromium it speaks the Chrome DevTools Protocol, the same protocol Chrome's DevTools use. For Firefox and WebKit, the Playwright team maintains lightly patched builds of those browsers that speak an equivalent protocol, which is why npx playwright install downloads its own browsers instead of using the ones on your machine. Because the connection is two-way, the browser can also tell Playwright things as they happen: a request was sent, a page navigated, a dialog opened, the console printed.

Your test tests/*.spec.ts runs in Node page.click(…) Playwright turns calls into protocol messages, waits, retries Chromium Chrome DevTools Protocol Firefox (patched) Playwright's protocol WebKit (patched) Playwright's protocol one open connection each: commands out, events back
Commands go out and events come back over one long-lived connection per browser.

Compare that with classic Selenium WebDriver: every command is a separate HTTP request to a driver program (chromedriver, geckodriver), which then talks to the browser. That's slower per step, and it's one-way: the test can only ask questions, so it has to keep asking ("is the button there yet? now?") to notice change. Newer Selenium can use WebDriver BiDi, a standard two-way protocol, which closes some of that gap. Cypress takes a third route: it runs your test code inside the browser, in the same page as your app. That gives it direct access to the app but ties it to one tab and one origin at a time, and to JavaScript only.

What Playwright's design buys you in practice:

  • Speed. No HTTP round trip per command, and browsers launch once per worker, not once per test (contexts make each test clean, below).
  • Reliable waiting. Playwright can check, inside the page, that an element is visible, stable and enabled right before it clicks, and knows about navigations and network requests as they happen.
  • Things outside the page. Network interception, several tabs, several users at once, downloads, permissions, geolocation, a fake clock: they're all controlled from the browser's side, not by injecting script into the page.
  • Real engines. WebKit is the engine inside Safari, so a WebKit run catches most Safari-only bugs, on Linux and Windows too. It isn't Safari itself (no Apple-specific features or system integration), which is worth saying in an interview.

#Browser, context and page

Added

Playwright has three levels, and knowing them explains most of how the test runner behaves:

  • A browser is the running browser process. Starting one takes a second or so, so the runner starts one per worker and reuses it.
  • A browser context is a brand-new, empty browser profile inside that browser: its own cookies, localStorage, sessionStorage, cache and permissions. Like a fresh incognito window, but you can have dozens at once in one browser, and each takes milliseconds to make.
  • A page is one tab in a context. Pages in the same context share cookies and storage (like two tabs in one window); pages in different contexts share nothing.

The test runner gives every test its own new context. That's what makes tests isolated: whatever one test does to cookies or storage is gone before the next test starts, even though both run in the same browser process. The mental model is a hotel: the browser is the building, each test checks into a freshly cleaned room (a context), and a page is a window in that room.

The Practice Shop keeps the signed-in user and the cart in localStorage, so you can watch isolation happen. The first test signs in and adds something to the cart; the second test opens the shop and finds itself signed out with an empty cart:

tests/isolation.spec.ts
import { test, expect } from "@playwright/test";

test("first test: signs in and fills the cart", async ({ page }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await page.getByRole("button", { name: "Add to cart" }).first().click();
  await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
});

test("second test: starts signed out, cart empty", async ({ page }) => {
  await page.goto("/practice/shop");
  // No signed-in user in this fresh context, so the shop sends us to sign in.
  await expect(page).toHaveURL(/\/practice\/\?next=/);
  expect(await page.evaluate(() => localStorage.length)).toBe(0);
});

test("two users at once: two contexts in one browser", async ({ browser }) => {
  const rohit = await (await browser.newContext()).newPage();
  const ana = await (await browser.newContext()).newPage();
  for (const [page, name] of [[rohit, "rohit"], [ana, "ana"]] as const) {
    await page.goto("/practice/");
    await page.getByLabel("Username").fill(name);
    await page.getByLabel("Password").fill("playwright");
    await page.getByRole("button", { name: "Sign in" }).click();
  }
  await expect(rohit.getByText("Signed in as rohit")).toBeVisible();
  await expect(ana.getByText("Signed in as ana")).toBeVisible();
});
npx playwright test
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/isolation.spec.ts:3:1 › first test: signs in and fills the cart (1.5s)
  ✓  2 [chromium] › tests/isolation.spec.ts:12:1 › second test: starts signed out, cart empty (64ms)
  ✓  3 [chromium] › tests/isolation.spec.ts:19:1 › two users at once: two contexts in one browser (1.1s)

  3 passed (3.0s)
What’s happening
  1. The first test signs in, which saves shop-user in localStorage, then adds the first product, which saves shop-cart. The cart link reads "Cart (1)".
  2. When the first test ends, the runner closes its context, and that context's localStorage, cookies and cache go with it.
  3. The second test gets a new, empty context. Opening /practice/shop finds no shop-user, so the shop redirects to the sign-in page with ?next=/practice/shop in the URL. page.evaluate() runs code in the page and confirms localStorage is empty.
  4. The third test asks for the browser fixture instead of page and makes two contexts itself. Rohit and Ana sign in side by side in the same browser process and don't see each other's session: two profiles, two users.
  5. The summary says "using 1 worker": all three tests are in one file, and by default tests in one file run one after another in the same worker (Chapter 12 covers parallelism). They're still isolated, because isolation comes from contexts, not from separate processes.
  6. This is why you never need "log out at the end of the test" or "clear the cart before the test": every test starts in a clean room. When tests do need to start signed in, you save the signed-in state once and load it into each new context (Chapter 8).
AdvancedIsolation is per context, not per server
Two tabs, one context

A test does const second = await page.context().newPage(); after signing in on page, then opens /practice/shop in second. Is second signed in?

Show answer

Yes. page.context() is the context page lives in, and newPage() on it opens another tab in the same profile. Both tabs share that context's localStorage, so second finds shop-user and shows the shop.

What’s happening
  1. Signing in on page writes shop-user into the context's localStorage for the shop's origin.
  2. page.context().newPage() opens a second tab in that same context.
  3. Pages in one context share cookies and storage, exactly like two tabs in one browser window, so the shop in second reads the same shop-user and stays on /practice/shop.
  4. If the test had used browser.newContext() instead, the new tab would be in a different profile and would be sent to sign in.

#Auto-waiting: why there are no sleeps

Added

Real pages are never ready all at once. The Practice Shop shows "Loading products…" for 0.7 seconds before the list appears; signing in takes 0.5 seconds; the "Added to your cart" message vanishes after 3 seconds. A test that acts the instant it can will click things that aren't there yet. The old fix was a sleep (wait 2 seconds, then click), which is either too short on a slow CI machine (the test fails at random) or too long everywhere else (the suite crawls).

Playwright's answer is auto-waiting, and it comes in two places:

  • Before every action, Playwright waits until the element is ready for it: attached to the page, visible, stable (not moving in an animation), able to receive the click (nothing covering it), enabled, editable for typing and, since 1.65, not inside an inert region. These are the actionability checks (Chapter 5).
  • In every expect(locator) assertion, Playwright re-checks until the condition is true or the timeout (5 seconds by default) runs out. That's what "web-first assertions" means (Chapter 6).

The mental model: a patient user. A person doesn't click a button that hasn't appeared yet; they look until it's there, then click. They don't decide the page is broken the moment they arrive; they give it a few seconds. Playwright does the same, automatically, and fails only when the thing never happens.

This test shows both halves, and also the one way to defeat auto-waiting by accident:

tests/waiting.spec.ts
import { test, expect } from "@playwright/test";

test.beforeEach(async ({ page }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
});

test("auto-waiting: the action and the assertion both wait", async ({ page }) => {
  // The list takes 0.7 s to load; click() waits for the button to exist and be ready.
  await page.getByRole("button", { name: "Add to cart" }).first().click();
  // The toast appears after the click; toHaveText keeps checking until it matches.
  await expect(page.getByRole("status").filter({ hasText: "Added" })).toHaveText("Added Mechanical Keyboard to your cart");
});

test("reading once does not wait", async ({ page }) => {
  // count() answers right now. The list hasn't loaded yet, so it's 0.
  const rightNow = await page.getByRole("listitem").count();
  console.log("products counted immediately:", rightNow);
  // The web-first assertion waits for the list instead.
  await expect(page.getByRole("listitem")).toHaveCount(8);
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/waiting.spec.ts:10:1 › auto-waiting: the action and the assertion both wait (1.5s)
products counted immediately: 0
  ✓  2 [chromium] › tests/waiting.spec.ts:17:1 › reading once does not wait (1.4s)

  2 passed (3.2s)
What’s happening
  1. beforeEach runs before each test: it signs in. The sign-in click starts a 500 ms "server call"; the next line in each test doesn't have to wait for it, because the actions and assertions after it wait for what they need.
  2. In the first test, getByRole("button", { name: "Add to cart" }).first() describes "the first Add to cart button". At that moment the shop may still be on the sign-in page or showing "Loading products…". click() waits until such a button exists, is visible, stable and enabled, then clicks it.
  3. The click adds the Mechanical Keyboard (the first product) and shows "Added Mechanical Keyboard to your cart" in a role="status" region. toHaveText re-checks that region until the text matches; it would fail only if the message never appeared in 5 seconds.
  4. In the second test, count() is not an assertion: it counts the matching elements once, right now, and returns a plain number. The page is still signing in or loading, so it prints 0. Any expect(number) on that value would fail, even though the page is about to be fine.
  5. await expect(page.getByRole("listitem")).toHaveCount(8) is the web-first version: it keeps counting until there are 8 or the timeout ends. The test passes.
  6. The rule this shows: ask the page through expect(locator), not by reading a value and checking it yourself. Reading once (count(), textContent(), isVisible()) is the most common cause of flaky Playwright tests.
AdvancedLook at the printed line

#Playwright vs Cypress vs Selenium

Added

All three drive a browser for end-to-end tests. The differences come from where the test code runs and how it talks to the browser, from the section above:

PlaywrightCypressSelenium WebDriver
Where your test code runsNode (or Python, Java, .NET), outside the browserinside the browser, next to your appoutside the browser, any language
How it controls the browserone two-way connection per browser (CDP, or Playwright's protocol for Firefox and WebKit)directly, as JavaScript in the pagean HTTP request per command to a driver; WebDriver BiDi in newer versions
BrowsersChromium, Firefox, WebKit (Safari's engine), plus branded Chrome and EdgeChrome-family, Firefox, WebKit (experimental)every browser with a driver, including real Safari
LanguagesTypeScript/JavaScript, Python, Java, .NETJavaScript/TypeScriptJava, Python, C#, JavaScript, Ruby, more
Waitingautomatic before actions and in assertionsautomatic retries of commands and assertionsexplicit waits you write yourself
Several tabs, windows, usersyes: pages and contextsone tab; other origins with cy.origin()yes, by switching windows
Parallel runsbuilt in (workers, sharding), freein CI with Cypress Cloud, or third-partySelenium Grid
Debuggingtrace viewer, UI Mode, codegentime-travel runner in the browseryour own logs and screenshots

When you'd pick each, which is the useful part in an interview:

  • Playwright for a new end-to-end suite on a web app: fast, parallel for free, all three engines, and isolated contexts make multi-user and multi-tab tests easy.
  • Cypress if the team already has a large, healthy Cypress suite, or values its in-browser interactive runner for front-end developers. Rewriting a working suite just to switch tools is rarely worth it.
  • Selenium when you need real Safari, real mobile browsers through Appium, a language Playwright doesn't support, or the company has a Selenium Grid and years of tooling built on it.
Which tool?

Your app's biggest customer complains about a bug that only happens in Safari on iPhone. Which tool lets you reproduce exactly that, and what can Playwright give you instead?

Show answer

Real iPhone Safari needs Selenium with Appium (or a device cloud) driving an actual device or the iOS Simulator. Playwright can't drive Apple's Safari app. What Playwright gives you is WebKit, Safari's engine, with an iPhone's screen size, user agent and touch support (devices["iPhone 15"]).

What’s happening
  1. Playwright's WebKit is built from the same open-source engine Safari uses, so layout, CSS and JavaScript engine bugs usually show up there too.
  2. It isn't Apple's Safari: no iOS system integration, no Safari-specific features outside WebKit, and on Linux it's WebKit with a different graphics stack.
  3. So the honest answer is: reproduce and guard it in Playwright with a WebKit mobile project (cheap, runs on every pull request), and confirm the fix once on a real device or simulator.

#Your turn: sign-in and waiting

Added

Open the Practice Shop yourself at rohit-playwright.pages.dev/practice/ (sign in as rohit, password playwright) and look around before you write tests for it. Chapter 2 sets up a project so you can run these on your machine.

Your turn: the locked account

Write a test that signs in as locked (password playwright) and checks the error message. What does the page say, and which locator finds it?

Show answer

The message is "This account is locked. Contact support." It's in an element with role="alert", so getByRole("alert") finds it:

tests/locked.spec.ts
import { test, expect } from "@playwright/test";

test("a locked account can't sign in", async ({ page }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("locked");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();

  await expect(page.getByRole("alert")).toHaveText("This account is locked. Contact support.");
  await expect(page).toHaveURL("/practice/");
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/locked.spec.ts:3:1 › a locked account can't sign in (961ms)

  1 passed (1.3s)
What’s happening
  1. The first three actions are the same as signing in as Rohit, with a different username.
  2. The shop waits half a second, then shows the message in its alert box. toHaveText waits for it, so there's no sleep.
  3. The second assertion checks the user stayed on the sign-in page. Without it, a bug that showed the message and signed the user in would still pass.
  4. role="alert" is how the page tells screen readers "announce this now", and it's what makes getByRole("alert") work. Testing through roles checks accessibility for free.
Your turn: predict the count

After signing in, a test runs console.log(await page.getByRole("listitem").count()) on the very next line, then await expect(page.getByRole("listitem")).toHaveCount(8). What does it print, and does the test pass?

Show answer

It prints 0 and the test passes. count() reads once, before the list has loaded; toHaveCount(8) waits until all 8 products are there. That's exactly the second test in "Auto-waiting" above, and you can see the 0 in its output.

What’s happening
  1. Clicking "Sign in" starts a 500 ms wait, then the shop page loads and waits another 700 ms before showing products.
  2. count() runs immediately and returns how many list items exist at that instant: none.
  3. toHaveCount(8) keeps checking until there are 8, well inside its 5-second timeout.
  4. If the test had done expect(await page.getByRole("listitem").count()).toBe(8), it would fail every time: the 0 is read once, and expect(0).toBe(8) has nothing to wait for.

Written fresh, no doc. Tests were run with @playwright/test 1.65.1 (Chrome for Testing 159, Firefox 159, WebKit 27.2) against the Practice Shop at /practice/; facts come from playwright.dev, read 2026-11-24.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.