Every interview answer and quiz card in Playwright, in one place: 90 interview answers and 49 quiz cards from 15 chapters. Try each one out loud before you open its answer; “Open in topic” takes you to the full explanation.
"Playwright is Microsoft's open-source browser automation library and test runner. One API drives Chromium, Firefox and WebKit, in TypeScript, JavaScript, Python, Java or .NET. For testing we use @playwright/test, which gives every test an isolated browser context, waits automatically before actions and in assertions, runs tests in parallel, and records traces you can step through when something fails. It's what most teams pick for new end-to-end suites now, because the tests are fast and much less flaky than the WebDriver-era tools."
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
Signing in on page writes shop-user into the context's localStorage for the shop's origin.
page.context().newPage() opens a second tab in that same context.
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.
If the test had used browser.newContext() instead, the new tab would be in a different profile and would be sent to sign in.
"Why did your team choose Playwright over Cypress?"
Show answer
Answer with the trade-offs that matter for your app rather than "it's better": "We needed to test a flow where an admin and a customer interact at the same time, plus a payment page on another origin. In Playwright those are two browser contexts and a normal navigation; in Cypress they fight its one-tab, one-origin model. We also wanted WebKit coverage for Safari users and parallel runs in CI without a paid service. Cypress's interactive runner is lovely for front-end debugging, but Playwright's trace viewer gave us that for CI failures too, which is where we actually needed it."
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
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.
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.
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.
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
The first three actions are the same as signing in as Rohit, with a different username.
The shop waits half a second, then shows the message in its alert box. toHaveText waits for it, so there's no sleep.
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.
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.
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
Clicking "Sign in" starts a 500 ms wait, then the shop page loads and waits another 700 ms before showing products.
count() runs immediately and returns how many list items exist at that instant: none.
toHaveCount(8) keeps checking until there are 8, well inside its 5-second timeout.
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.
In your copy, open practice-shop/practice/practice.js and find the line with p.name.toLowerCase().includes(q) (the search filter). Delete .toLowerCase() so it reads p.name.includes(q), save, and run npx playwright test. Predict what happens before you run it. Then put .toLowerCase() back and run again.
Show answer
The test fails. Search becomes case-sensitive, so "mouse" no longer matches "Wireless Mouse" or "Vertical Mouse", and the shop shows no products. After the 5-second assertion timeout Playwright reports what it expected and what it got. These are the key lines from doing exactly this on 24 Nov 2026:
Output
✘ 1 [chromium] › tests/shop.spec.ts:3:1 › rohit can sign in and search for a mouse (6.0s)
Error: expect(locator).toHaveCount(expected) failed
Locator: getByRole('listitem')
Expected: 2
Received: 0
Timeout: 5000ms
Put .toLowerCase() back and it passes again (1 passed).
What’s happening
The shop lowercases what you type (q) and, before your change, each product name too, so "mouse" matched "Mouse". Without .toLowerCase() on the name, it compares "mouse" with "Wireless Mouse" letter for letter, and capital M doesn't match.
Your test still types "mouse" and expects 2 products. toHaveCount(2) re-counts for up to 5 seconds and finds 0 every time, then fails, telling you it expected 2 and received 0.
That's a realistic bug (case-sensitive search) caught by a test that never mentions case. It caught it because it checks the outcome a user cares about: searching for a mouse finds the mice.
Putting the line back and seeing the test pass again closes the loop: you've shown the test fails when the feature breaks and passes when it works, the first two items of the checklist in Chapter 3.
Try other breaks the same way: change the express fee in EXPRESS_FEE, remove the disabled from the sold-out button, or change a label in shop.html, and see which tests notice. A change no test notices is a gap in your suite.
"Playwright emulates devices: a project with devices['iPhone 17'] or devices['Pixel 10'] gets the viewport, pixel ratio, touch events, isMobile and user agent, running in WebKit or Chromium. That catches responsive layout and touch bugs cheaply on every pull request. It's emulation, not a real phone: no real iOS Safari, no real device performance or OS keyboards, so for those we'd run a small smoke suite on real devices through a device cloud."
Write a test that signs in as ana, opens the "Category" filter, picks "Audio", and checks that exactly two products show, the headphones and the microphone.
Running 1 test using 1 worker
✓ 1 [chromium] › tests/category.spec.ts:3:1 › the Audio category shows the two audio products (1.8s)
1 passed (2.4s)
What’s happening
Signing in is the same as before, with Ana this time.
selectOption("Audio") picks the option whose label or value is "Audio". It waits for the option to exist, which matters here: the shop adds category options only after the products have loaded.
Filtering is instant (no debounce), so the list goes from 8 to 2 at once. toHaveCount(2) passes.
toHaveText with an array checks the cards in order. If the shop listed the microphone first, this assertion would fail, which is what you want only if order matters. If it doesn't, check each one with toContainText instead.
Change the expected count to 3 and run it again. What does Playwright print, and how long does the test take to fail?
Show answer
The test fails after about 7 seconds: under 2 s to sign in and filter, then the full 5-second assertion timeout. The error says what it expected, what it found, and where:
Running 1 test using 1 worker
✘ 1 [chromium] › tests/category.spec.ts:3:1 › the Audio category shows three products (wrong on purpose) (6.7s)
1) [chromium] › tests/category.spec.ts:3:1 › the Audio category shows three products (wrong on purpose)
Error: expect(locator).toHaveCount(expected) failed
Locator: getByRole('listitem')
Expected: 3
Received: 2
Timeout: 5000ms
Call log:
- Expect "toHaveCount" getByRole('listitem') with timeout 5000ms
- waiting for getByRole('listitem')
14 × locator resolved to 2 elements
- unexpected value "2"
7 | await page.getByRole("button", { name: "Sign in" }).click();
8 | await page.getByLabel("Category").selectOption("Audio");
> 9 | await expect(page.getByRole("listitem")).toHaveCount(3);
| ^
10 | });
11 |
at <project>/tests/category.spec.ts:9:44
Error Context: test-results/category-the-Audio-categor-2caad--products-wrong-on-purpose--chromium/error-context.md
1 failed
[chromium] › tests/category.spec.ts:3:1 › the Audio category shows three products (wrong on purpose)
What’s happening
toHaveCount(3) keeps re-counting for 5 seconds, hoping the page will change. It never does, so it fails.
The error names the assertion, the locator, the expected value (3), the received value (2), and the timeout. The "Call log" shows how many times it counted in those 5 seconds (14 on this run), finding 2 elements every time.
The code frame points at the exact line with >, and "Error Context" is a file with the page's accessibility snapshot at the moment of failure: often enough to see what went wrong without re-running.
Five seconds is the cost of a wrong assertion: a failing web-first assertion always takes its full timeout. That's why you don't raise expect.timeout to 30 seconds to "fix" flakiness: every real failure then takes 30 seconds to report.
"What's the difference between a unit test and an E2E test, and when do you write each?"
Show answer
"A unit test checks one piece of logic in isolation, in milliseconds, and when it fails it points at the exact function. An E2E test drives the real app in a real browser, so it proves the pieces work together for a user, but it's slower and points less precisely. I put the detail (every validation rule, every pricing edge case) in unit and API tests, and use E2E for the critical journeys and for wiring that only shows up end to end: sign-in, search, checkout, the flows where a break costs money or trust. If a bug could only be caught end to end, that's an E2E test; if it could be caught lower, it goes lower."
"Each test creates the data it needs, through the API, with unique names, so tests can run in parallel and in any order. Things that are expensive to create, like a signed-in session, are created once per worker and reused read-only. We never point tests at shared mutable accounts. And we run with fullyParallel and occasionally --shuffle in CI, so a hidden dependency between tests shows up as a failure quickly instead of hiding for months."
"It tests one user-visible behaviour on an important journey, named for that behaviour. It sets up its own state so it can run alone, in parallel, in any order. It finds elements the way a user would, by role and label, so refactors don't break it. It has no fixed waits: actions and web-first assertions wait for the page. And it asserts the outcome the user cares about, specific enough that it would actually fail if the feature broke. I check that last part by breaking the feature on purpose once and watching the test fail."
Using the four kinds of case (happy path, rules, edges, failures), list cases for the cart page and decide which are E2E. Try it before you open the answer.
Show answer
One reasonable plan (yours can differ; what matters is that every case has a "where" and a reason):
Case
Expect
Where
Happy path: two different products added
two rows, total is the sum
E2E
Rule: + raises quantity and subtotal
quantity 2, subtotal doubles, total updates
E2E (one test)
Rule: − to zero removes the row
row gone, total updates
E2E
Edge: removing the last item
"Your cart is empty." and a "Browse products" link
E2E
Edge: prices with cents ($74.99 × 3)
$224.97, no rounding error
unit test of the total
Edge: the cart survives a reload
same rows after page.reload()
E2E (it's storage)
Failure: not signed in
sent to sign in, back to the cart after
E2E, with the sign-in tests
What’s happening
The happy path checks the page shows what was added, with the right total.
The two rules (+ and −) are the page's whole job, so each gets a short E2E test; the arithmetic for every price combination goes to a unit test.
The edges are where carts really break: emptying it, money with cents, a reload. Only the money rounding is better as a unit test, because it's pure logic with many inputs.
"Not signed in" is true of every page, so it's tested once, with sign-in, rather than on each page.
Write the "removing the last item" test and the "cart survives a reload" test. Each must arrange its own state.
Show answer
tests/cart.spec.ts
import{ test, expect,typePage}from"@playwright/test";asyncfunctionsignInWithCart(page: Page,...products:string[]){await page.goto("/practice/");await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();for(const name of products){await page.getByRole("listitem").filter({ hasText: name }).getByRole("button",{ name:"Add to cart"}).click();}await page.getByRole("link",{ name:`Cart (${products.length})`}).click();}test("removing the last item shows the empty cart",async({ page })=>{awaitsignInWithCart(page,"USB Microphone");await page.getByRole("button",{ name:"Remove USB Microphone"}).click();awaitexpect(page.getByText("Your cart is empty.")).toBeVisible();awaitexpect(page.getByRole("link",{ name:"Browse products"})).toBeVisible();awaitexpect(page.getByRole("link",{ name:"Cart (0)"})).toBeVisible();});test("the cart survives a reload",async({ page })=>{awaitsignInWithCart(page,"Compact Keyboard","Monitor Light Bar");await page.reload();awaitexpect(page.getByRole("row",{ name:/Compact Keyboard/})).toBeVisible();awaitexpect(page.getByRole("row",{ name:/Monitor Light Bar/})).toBeVisible();awaitexpect(page.getByTestId("cart-total")).toHaveText("$108.00");});
npx playwright test
Running 2 tests using 1 worker
✓ 1 [chromium] › tests/cart.spec.ts:14:1 › removing the last item shows the empty cart (1.6s)
✓ 2 [chromium] › tests/cart.spec.ts:24:1 › the cart survives a reload (1.5s)
2 passed (3.6s)
What’s happening
Both tests use the same arrange helper, which signs in as Ana, adds the products, and opens the cart by clicking the header link, so it also proves the count was right.
The first test removes the only item, then checks three facts: the empty message, the link back to the shop, and the header count of 0. Checking only the message would miss a header that still said "Cart (1)".
The second test reloads the page. If the cart lived only in memory, the rows would vanish; because the shop keeps it in localStorage (in this test's context), both rows and the $108.00 total ($59.00 + $49.00) come back.
Neither test depends on the other or on any earlier test: run either alone with npx playwright test -g "reload" and it passes.
"What's the difference between a locator and an element handle?"
Show answer
"A locator is a lazy description: Playwright resolves it every time it's used, waits for it to be actionable, and insists it matches exactly one element for actions. An element handle is a reference to one specific DOM node, found once. If the framework re-renders, the handle points at a detached node and fails, and if two elements matched, a handle silently takes the first. So I use locators everywhere; handles only survive in old code."
For each, pick a locator: (a) the "Place order" button, (b) the "Email" field on checkout, (c) the checkout total, which is a number with no label, (d) the "Your cart is empty." message.
A button has a role and a name, so role comes first; it also proves a screen reader can find it.
A form field is identified by its label, which is exactly how a user finds it.
The total's text is the value you want to check, so you can't find it by its text. Nothing user-facing names it, which is when a test id is the right tool.
A message is non-interactive text, so getByText is the natural fit. (If it were in a role="status" or role="alert" region, getByRole("alert") would also work and checks the region's role.)
"Because it finds elements the way users and screen readers do, by what the element is and what it's called. It survives refactors that don't change what the user sees, it fails when they do, and it quietly checks accessibility: if I can't find the Save button by role and name, a screen-reader user can't either, and that's a bug worth knowing about. When the name is surprising, I print ariaSnapshot() to see the computed name instead of reaching for CSS."
"I find the row by its key, with getByRole('row', { name: /ORD-1002/ }) or a filter on the row header, then go into it for the cell or button I need. I avoid nth on rows unless the order is what I'm testing. For a cell by column, either the column order is part of the design and I count cells (remembering that a <th scope=row> is a rowheader, not a cell), or I compute the index from the column headers so the test survives a column being added."
Which of these needs frameLocator: (a) the "Subscribe" button, (b) the "Send" button, (c) the "Delete account" button?
Show answer
Only (b), the chat's "Send" button, because it's in an iframe. (a) is in a shadow root, which locators pierce automatically, and (c) is in the main document.
What’s happening
An iframe is a separate document; locators on page never look inside one.
An open shadow root is part of the same document, just encapsulated; Playwright's locators (except XPath) walk into it.
If you're unsure, the aria snapshot of the main page shows an iframe entry with nothing inside it for (b), while (a)'s text box and button appear inline.
"I use what the user sees: role and accessible name first, then label, then text. Those survive markup refactors and fail when the user-facing behaviour changes, which is exactly when I want a failure. For things with no stable user-facing handle, like a price cell or a chart, I agree test ids with the developers as a contract. I avoid CSS paths, XPath and nth on lists whose order isn't the point. And when a locator gets complicated, that's usually an accessibility smell in the page: a button with no name, a form field with no label. I'd rather fix the page than write a clever selector."
This line fails on the shop page with "strict mode violation: getByRole('button', { name: 'Add to cart' }) resolved to 8 elements". Write a test that adds the Compact Keyboard instead, with no nth, first or last, and checks the cart has it.
await page.getByRole("button", { name: "Add to cart" }).click();
Show answer
Narrow by the product card first, then find the button inside it:
tests/strict-fix.spec.ts
import{ test, expect,typePage}from"@playwright/test";asyncfunctionsignIn(page: Page, path ="/practice/shop"){await page.goto(path);await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();awaitexpect(page).toHaveURL(path);}test("adds the Compact Keyboard by its card, not its position",async({ page })=>{awaitsignIn(page);const card = page.getByRole("listitem").filter({ has: page.getByRole("heading",{ name:"Compact Keyboard"})});await card.getByRole("button",{ name:"Add to cart"}).click();await page.getByRole("link",{ name:"Cart (1)"}).click();awaitexpect(page.getByRole("row",{ name:/Compact Keyboard/})).toBeVisible();awaitexpect(page.getByTestId("cart-total")).toHaveText("$59.00");});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/strict-fix.spec.ts:11:1 › adds the Compact Keyboard by its card, not its position (1.8s)
1 passed (2.3s)
What’s happening
The original locator is fine as a description, it just describes eight buttons. Strictness turns that into a clear error instead of a silent click on the first one.
filter({ has: getByRole("heading", { name: "Compact Keyboard" }) }) picks the one card containing that heading, and chaining getByRole("button", …) finds the button inside that card only.
The check goes past "the click happened": the header link says "Cart (1)", the cart has a Compact Keyboard row, and the total is its price, $59.00.
Re-sorting or adding products wouldn't change which card this finds, which is the difference from nth(1).
With the three past orders below in localStorage, write a test that checks ORD-1003 has 3 items and a total of $216.00, and that the table has exactly three orders. Find the row by its order id.
Running 1 test using 1 worker
✓ 1 [chromium] › tests/orders.spec.ts:11:1 › ORD-1003 shows its items and total (996ms)
1 passed (1.4s)
What’s happening
addInitScript seeds the order history before the account page's script reads it, so the table has three rows.
The row is found by its row header, ORD-1003, using filter({ has }). That's stricter than getByRole("row", { name: /ORD-1003/ }), which would also match a row that merely mentioned ORD-1003 in another cell.
order.getByRole("cell") gives the three data cells (the order id is a row header, not a cell), and one array assertion checks the date, the item count and the total in order: 216 is shown as $216.00.
Counting row headers in the table gives the number of orders, 3; the header row has column headers only, so it isn't counted.
Write one test on the account page that (1) sends "Hello" in the support chat and waits for the reply, and (2) tries to subscribe to the newsletter with rohit@ and checks the error.
Show answer
tests/frame-and-shadow.spec.ts
import{ test, expect,typePage}from"@playwright/test";asyncfunctionsignIn(page: Page, path ="/practice/shop"){await page.goto(path);await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();awaitexpect(page).toHaveURL(path);}test("chat in the iframe, newsletter in the shadow root",async({ page })=>{awaitsignIn(page,"/practice/account");const chat = page.getByTitle("Support chat").contentFrame();await chat.getByPlaceholder("Type a message").fill("Hello");await chat.getByRole("button",{ name:"Send"}).click();awaitexpect(chat.getByRole("listitem")).toHaveText([/Hi! How can we help/,"You: Hello",/A human will reply/]);await page.getByLabel("Email for newsletter").fill("rohit@");await page.getByRole("button",{ name:"Subscribe"}).click();awaitexpect(page.getByRole("region",{ name:"Newsletter"}).getByRole("status")).toHaveText("Enter a valid email.");});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/frame-and-shadow.spec.ts:11:1 › chat in the iframe, newsletter in the shadow root (2.4s)
1 passed (2.8s)
What’s happening
getByTitle("Support chat").contentFrame() enters the iframe; getByPlaceholder("Type a message") finds the message box by its placeholder (its label is visually hidden, so getByLabel("Message") would work too).
After Send, the conversation has the greeting, your message, and, a second later, the reply. The array assertion waits for all three in order.
The newsletter's field and button are in an open shadow root, so ordinary locators reach them. rohit@ fails the component's email check.
The status message is also inside the shadow root. Scoping to the "Newsletter" region keeps it from matching the page's other status messages (there are three more on the account page), which would be a strict mode violation.
"That the element is attached, visible, stable (not animating), enabled, actually the thing under the pointer, and, since 1.65, not inside an inert region. It keeps retrying those checks until they pass or the timeout ends, and the error's call log says which check failed: 'element is not enabled', or 'some div intercepts pointer events'. Typing with fill also checks the field is editable. Key presses and file uploads only wait for the element to exist. That's why I don't write sleeps before clicks: the click already waits for exactly the conditions a user would."
"When would you use an explicit wait in Playwright?"
Show answer
"Rarely, because actions wait for actionability and assertions retry. I add one when the next step depends on something no locator covers: waitForResponse when I need the API response or nothing visible changes, waitForURL before a goto that would otherwise race a click's navigation, waitForEvent for popups, downloads and dialogs, started before the action. I don't use networkidle, which the docs discourage, and waitForTimeout never goes into a committed test: a fixed sleep is either too short on a slow machine or wasted time on a fast one."
"A test fails with 'element intercepts pointer events'. What do you do?"
Show answer
"First, read which element intercepts: the call log names it. Usually it's something a user would also hit: a cookie banner, a toast, a modal that didn't close, a sticky header over the target after scrolling. Then I fix the cause: close the banner the way a user would, wait for the toast or modal to disappear, or report the layout bug. I don't add force: true, because the browser would deliver the click to the overlay anyway, and the test would stop telling me a real user is stuck."
On checkout, type BOGUS into "Promo code", press Enter, wait for the shop's request to come back, and check its status and the message the user sees. (Put any product in the cart first.)
Running 1 test using 1 worker
✓ 1 [chromium] › tests/promo.spec.ts:11:1 › an unknown promo code is rejected (1.9s)
1 passed (2.4s)
What’s happening
The arrange part puts the Standing Desk Mat ($39.00) in the cart and opens checkout.
waitForResponse takes a predicate here, matching any promo request, and is started before press("Enter"), the key the shop listens for.
The response is a 404, and its URL shows the shop upper-cased the code to BOGUS. Those are facts about the request, which only waitForResponse can check.
Then what the user sees: the "isn't valid" message (with the shop's curly apostrophe), and a total with no discount, still $39.00.
Upload a GIF called cat.gif (8 KB, made in memory) and check the message and that the preview image now has a blob: source. Then upload a PDF and check it's rejected and the input is empty again.
Show answer
tests/uploads.spec.ts
import{ test, expect,typePage}from"@playwright/test";asyncfunctionsignIn(page: Page, path ="/practice/shop"){await page.goto(path);await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();awaitexpect(page).toHaveURL(path);}test("a GIF is accepted, a PDF is not",async({ page })=>{awaitsignIn(page,"/practice/account");const picture = page.getByLabel("Profile picture");const message = page.getByText(/^(Uploaded|Please choose)/);await picture.setInputFiles({ name:"cat.gif", mimeType:"image/gif", buffer: Buffer.alloc(8*1024)});awaitexpect(message).toHaveText("Uploaded cat.gif (8 KB).");awaitexpect(page.getByAltText("Your profile picture")).toHaveAttribute("src",/^blob:/);await picture.setInputFiles({ name:"receipt.pdf", mimeType:"application/pdf", buffer: Buffer.from("%PDF-1.7")});awaitexpect(message).toHaveText("Please choose an image file (PNG, JPG or GIF).");awaitexpect(picture).toHaveValue("");});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/uploads.spec.ts:11:1 › a GIF is accepted, a PDF is not (1.0s)
1 passed (1.5s)
What’s happening
setInputFiles with a buffer creates the file in memory: the name and MIME type are what the page sees. 8 × 1024 bytes is reported as 8 KB.
The message locator matches either outcome by its start, so one locator follows the status line through both uploads.
After the GIF, the preview image's src is a blob: URL the shop made from the file, which proves the page actually used it, not just printed a message.
The PDF's type is application/pdf, so the shop rejects it and resets the input; toHaveValue("") checks nothing is left selected.
Your turn: reorder with the buttons, then by dragging
On the account page, move "USB Microphone" to the top using its "Move … up" button, then drag "Standing Desk Mat" onto "USB Microphone". Check the order after each step and after a reload.
Show answer
tests/wishlist.spec.ts
import{ test, expect,typePage}from"@playwright/test";asyncfunctionsignIn(page: Page, path ="/practice/shop"){await page.goto(path);await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();awaitexpect(page).toHaveURL(path);}test("the wishlist can be reordered both ways and stays reordered",async({ page })=>{awaitsignIn(page,"/practice/account");const wishes = page.getByRole("list",{ name:"Wishlist"}).getByRole("listitem");await page.getByRole("button",{ name:"Move USB Microphone up"}).click();awaitexpect(wishes).toHaveText([/USB Microphone/,/Monitor Light Bar/,/Standing Desk Mat/]);awaitexpect(page.getByRole("button",{ name:"Move USB Microphone up"})).toBeDisabled();await wishes.filter({ hasText:"Standing Desk Mat"}).dragTo(wishes.filter({ hasText:"USB Microphone"}));awaitexpect(wishes).toHaveText([/Standing Desk Mat/,/USB Microphone/,/Monitor Light Bar/]);await page.reload();awaitexpect(wishes).toHaveText([/Standing Desk Mat/,/USB Microphone/,/Monitor Light Bar/]);});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/wishlist.spec.ts:11:1 › the wishlist can be reordered both ways and stays reordered (1.2s)
1 passed (1.7s)
What’s happening
The "Move USB Microphone up" button swaps it with the item above, so it goes from second to first. Now that it's at the top, its "up" button is disabled, which is worth checking: it's a rule of the feature.
Dragging the Standing Desk Mat onto the USB Microphone (now first) moves the mat into first place, pushing the others down.
The reload proves both changes were saved, not just drawn.
Testing the buttons as well as dragging matters: the buttons are how keyboard and screen-reader users reorder, and they're the more reliable path to test.
"It's an assertion that retries against the live page until the condition holds or the timeout runs out, 5 seconds by default. await expect(locator).toHaveText('…') keeps re-resolving the locator and re-reading the text, so it doesn't matter whether the update arrives in 10 milliseconds or 3 seconds. The contrast is expect(await locator.textContent()).toBe('…'), which reads once and fails if it read too early. The rule I follow: anything on the page goes through expect(locator) or expect(page); plain expect(value) only for values I already have, like a response status or a computed number."
"How do you wait for something that isn't in the DOM?"
Show answer
"expect.poll with a function that fetches it: page.evaluate for browser storage, the request fixture for an API, a DB helper for data. It retries with backoff until the matcher passes or the timeout ends, so it's a web-first assertion for any value. When I need to repeat several steps together, like reload-then-check, I use expect(async () => { … }).toPass({ timeout }), with short inner timeouts and only idempotent steps inside. And I always give toPass a timeout, because its default is 0, which means it runs until the test times out."
Which of these lines can flake, and what would you write instead? (a) expect(await page.getByTestId("cart-total").textContent()).toBe("$59.00") (b) expect(response.status()).toBe(200) (c) expect(await page.title()).toBe("Cart · Practice Shop")
Show answer
(a) and (c) can flake; (b) is fine. Write await expect(page.getByTestId("cart-total")).toHaveText("$59.00") and await expect(page).toHaveTitle("Cart · Practice Shop").
What’s happening
(a) reads the total once. If the cart is still re-rendering, it gets the old total.
(b) checks a response the test already has: a status code never changes after the fact, so a plain expect is correct.
(c) reads the title once, and titles often change after navigation or when a page loads data (the shop's order page sets its title from the order). toHaveTitle retries.
The answer keeps the original too, marked with test.fail(), which tells Playwright the test is expected to fail: the run reports a problem only if it unexpectedly passes. It's a handy way to prove a bad version really is bad.
tests/fix-flaky.spec.ts
import{ test, expect,typePage}from"@playwright/test";asyncfunctionsignIn(page: Page, path ="/practice/shop"){await page.goto(path);await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();awaitexpect(page).toHaveURL(path);}test("the original, which reads values once",async({ page })=>{
test.fail();// expected to failawaitsignIn(page);await page.getByLabel("Search products").fill("phone");expect(await page.getByRole("listitem").count()).toBe(2);await page.getByRole("button",{ name:"Add to cart"}).first().click();expect(await page.getByRole("link",{ name:/Cart/}).textContent()).toBe("Cart (1)");});test("searching for phone and adding the first result",async({ page })=>{awaitsignIn(page);const products = page.getByRole("list",{ name:"Products"}).getByRole("listitem");await page.getByLabel("Search products").fill("phone");awaitexpect(products.getByRole("heading")).toHaveText(["Noise-Cancelling Headphones","USB Microphone"]);await products.first().getByRole("button",{ name:"Add to cart"}).click();awaitexpect(page.getByRole("link",{ name:/Cart/})).toHaveText("Cart (1)");awaitexpect(page.getByRole("status").filter({ hasText:"Added"})).toHaveText("Added Noise-Cancelling Headphones to your cart");});
npx playwright test
Running 2 tests using 1 worker
✘ 1 [chromium] › tests/fix-flaky.spec.ts:11:1 › the original, which reads values once (967ms)
✓ 2 [chromium] › tests/fix-flaky.spec.ts:20:1 › searching for phone and adding the first result (1.7s)
2 passed (3.1s)
What’s happening
The original fails at its first expect: right after signing in, the products are still loading, and even once they arrive the search applies 0.3 s later. count() reads whatever is there at that instant, and it's never 2. test.fail() turns that failure into the expected result: the list shows it with a ✘, but the summary counts it among the "2 passed".
The fix replaces the count with one web-first assertion on the headings, which checks there are exactly two results and which two, waiting for both the products and the search.
The original's getByRole("button", { name: "Add to cart" }).first() would click the first button on the page, whatever it is; chaining from products.first() makes it clear it's the first search result.
toHaveText("Cart (1)") retries instead of reading once, and the toast check proves the right product was added: the headphones.
On the account page, move "Standing Desk Mat" up once with its button, then use expect.poll to check the order the shop saved in localStorage (key shop-wishlist, a JSON array of names).
Show answer
tests/wishlist-poll.spec.ts
import{ test, expect,typePage}from"@playwright/test";asyncfunctionsignIn(page: Page, path ="/practice/shop"){await page.goto(path);await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();awaitexpect(page).toHaveURL(path);}test("moving an item up saves the new order",async({ page })=>{awaitsignIn(page,"/practice/account");await page.getByRole("button",{ name:"Move Standing Desk Mat up"}).click();await expect
.poll(()=> page.evaluate(()=>JSON.parse(localStorage.getItem("shop-wishlist")??"null"))).toEqual(["Monitor Light Bar","Standing Desk Mat","USB Microphone"]);awaitexpect(page.getByRole("list",{ name:"Wishlist"}).getByRole("listitem")).toHaveText([/Monitor/,/Standing/,/USB/]);});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/wishlist-poll.spec.ts:11:1 › moving an item up saves the new order (1.0s)
1 passed (1.4s)
What’s happening
Before the move, nothing is saved: the shop only writes shop-wishlist when the order changes, so the key is missing and the function returns null (hence the ?? "null").
After "Move Standing Desk Mat up", the shop saves the new order. expect.poll keeps calling the function until the array equals the expected order, and toEqual compares arrays element by element.
The last assertion checks the same order on screen. Storage and screen agreeing is the real proof: either alone could be right while the other is wrong.
Your turn: a soft checklist for the confirmation page
Place an order for one Compact Keyboard with Express delivery and check four facts on the confirmation page with soft assertions, each with a custom message: the heading, the order number, the total ($68.99) and that the delivery estimate is shown. All four should pass.
Show answer
tests/confirmation.spec.ts
import{ test, expect,typePage}from"@playwright/test";asyncfunctionsignIn(page: Page, path ="/practice/shop"){await page.goto(path);await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();awaitexpect(page).toHaveURL(path);}test("the confirmation page shows everything about the order",async({ page })=>{awaitsignIn(page);await page.getByRole("listitem").filter({ hasText:"Compact Keyboard"}).getByRole("button",{ name:"Add to cart"}).click();await page.goto("/practice/checkout");await page.getByLabel("Email").fill("ana@example.com");await page.getByLabel("Delivery address").fill("4 Queen Street, Toronto");await page.getByLabel("Express").check();await page.getByLabel("I agree to the terms").check();await page.getByRole("button",{ name:"Place order"}).click();awaitexpect(page).toHaveURL(/\/practice\/order\?id=ORD-1001$/);// a gate: nothing below makes sense without itawait expect.soft(page.getByRole("heading",{ level:1}),"thanks the customer by first name").toHaveText("Thank you, Ana!");await expect.soft(page.getByText("Your order ORD-1001 is confirmed."),"shows the order number").toBeVisible();await expect.soft(page.getByText("Total paid on delivery: $68.99"),"charges the keyboard plus express delivery").toBeVisible();await expect.soft(page.getByTestId("delivery-estimate"),"estimates a delivery date").toHaveText(/^Estimated delivery: \w+day, \w+ \d+$/);});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/confirmation.spec.ts:11:1 › the confirmation page shows everything about the order (3.2s)
1 passed (3.6s)
What’s happening
The arrange part places the order: one Compact Keyboard ($59.00) with Express ($9.99), so the total should be $68.99.
The URL check is a normal assertion on purpose: if the order wasn't placed, the four checks below would all fail for the same reason, so it's a gate before the checklist.
The four soft assertions are independent facts about the same screen. If two were wrong, one run would report both, each under its own message.
The delivery date depends on today's date, so the test matches its shape with a regex ("Thursday, November 26" style) rather than an exact date. Chapter 11's clock API makes the exact date testable.
"What's the difference between beforeAll and beforeEach, and what goes wrong with beforeAll?"
Show answer
"beforeEach runs before every test, in that test's fresh context, so it's safe for per-test setup like signing in or opening a page. beforeAll runs once per worker process, before the first test that worker runs, and again whenever a failure restarts the worker. People use it for 'run once' setup and then find it runs several times in parallel or after a failure, or they create state in it that tests then share and change. I use fixtures instead: test-scoped for per-test setup, worker-scoped for expensive per-worker setup, and a setup project for true once-per-run work like logging in."
"How do you structure a large Playwright suite: fixtures, page objects, or helpers?"
Show answer
"All three, for different jobs. Page objects model the pages: locators and user-level actions, no assertions about the test's purpose, one class per page or component. Fixtures provide the starting state and clean it up: a signed-in page, a seeded user, a page object already on the right page; they compose, they're lazy, and teardown runs even when a test fails, which beforeEach/afterEach don't give you as cleanly. Helpers are small pure functions like formatting money or generating unique data. So a test asks for { cart } and reads as act and assert. On top of that, authentication comes from a setup project with saved storage state, test data is created per test through the API, and options let projects run the same tests as different users or locales."
"Your E2E suite passes alone but fails when run in parallel. What do you look for?"
Show answer
"Shared state. Usually it's a shared account or shared data: two tests change the same user's cart, or one test asserts a count while another adds to it. Sometimes it's order dependence: a test that only passes because an earlier one created something. I'd run with --workers=1 to confirm it's an interaction, then --repeat-each and --shuffle to find the pair. The fix is to give each test its own data through a fixture (unique names, created through the API, cleaned up in teardown) and each worker its own account if tests change account state, so the suite is correct at any level of parallelism."
Write an AccountPage page object for /practice/account with the "Display name" field, a saveDisplayName(name) method and a message locator for the status text. Use it in a test that signs in as ana, saves "Ana P." and checks the message "Saved. You’ll appear as “Ana P.”." Then reload and check the field still shows "Ana P.".
import{ test, expect }from"@playwright/test";import{ AccountPage }from"../pages/account-page";test("a saved display name is shown and kept after a reload",async({ page })=>{await page.goto("/practice/");await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();awaitexpect(page.getByText("Signed in as ana")).toBeVisible();const account =newAccountPage(page);await account.goto();awaitexpect(account.displayName).toHaveValue("Ana");await account.saveDisplayName("Ana P.");awaitexpect(account.message).toHaveText("Saved. You’ll appear as “Ana P.”.");await page.reload();awaitexpect(account.displayName).toHaveValue("Ana P.");});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/account.spec.ts:4:1 › a saved display name is shown and kept after a reload (1.1s)
1 passed (1.6s)
What’s happening
The page object holds two locators and two actions, all in user terms. message is narrowed with filter({ hasText: "Saved" }) because the account page has several role="status" elements (the avatar message, the danger-zone message, the newsletter one inside its shadow root), and an unfiltered getByRole("status") would match more than one and fail strict mode.
The test waits for "Signed in as ana" before going to the account page. Without it, goto could run before the sign-in finished, and the account page would redirect to sign-in.
Before saving, the field shows "Ana" (the shop's default display name is the user's name), which proves the starting state.
After saving, the message uses the shop's curly quotes and apostrophe exactly (You’ll, “Ana P.”), so the expected string must too; a straight ' wouldn't match.
After page.reload(), the field still says "Ana P.", because the shop saved it in localStorage. The assertions stay in the test; the page object only knows how to use the page.
Turn the sign-in into a fixture: an option user (default "rohit") and a fixture account that signs in as user and hands the test an AccountPage already open. Write two tests: one with the default user checking the field shows "Rohit", and one in a describe with test.use({ user: "ana" }) checking it shows "Ana".
import{ test as base, expect }from"@playwright/test";import{ AccountPage }from"./pages/account-page";exportconst test = base.extend<{ user:string; account: AccountPage }>({
user:["rohit",{ option:true}],account:async({ page, user }, use)=>{await page.goto("/practice/");await page.getByLabel("Username").fill(user);await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();awaitexpect(page.getByText(`Signed in as ${user}`)).toBeVisible();const account =newAccountPage(page);await account.goto();awaituse(account);},});export{ expect };
tests/account.spec.ts
import{ test, expect }from"../fixtures";test("the display name defaults to the user's name",async({ account })=>{awaitexpect(account.displayName).toHaveValue("Rohit");});
test.describe("as Ana",()=>{
test.use({ user:"ana"});test("Ana's display name defaults to Ana",async({ account })=>{awaitexpect(account.displayName).toHaveValue("Ana");});});
npx playwright test
Running 2 tests using 1 worker
✓ 1 [chromium] › tests/account.spec.ts:3:1 › the display name defaults to the user's name (1.0s)
✓ 2 [chromium] › tests/account.spec.ts:10:3 › as Ana › Ana's display name defaults to Ana (992ms)
2 passed (2.5s)
What’s happening
user: ["rohit", { option: true }] is the option; account depends on page and user, signs in, waits for the header, opens the account page and hands over the page object.
The first test uses the default, so it's signed in as rohit and the field shows "Rohit".
The describe overrides the option with test.use({ user: "ana" }); the same fixture now signs in as ana, and the field shows "Ana".
Neither test has any arrange code: each asks for account and asserts. Adding a third user is a three-line describe, not a copy of the sign-in steps.
"How do you handle authentication in a large Playwright suite?"
Show answer
"I sign in once in a setup project and save the storage state to a gitignored file; the test projects depend on setup and load that state, so tests start signed in without touching the login form. Each test still has its own context, so they stay isolated. For several roles, setup saves one file per role and tests pick one with test.use, or open one context per role when a test needs both. If tests change account data, I give each worker its own account with a worker-scoped fixture that overrides storageState. And the login form itself gets its own focused tests that start signed out."
"First I'd separate testing the login from being logged in: almost every test gets a saved session from a setup project, so MFA only affects the setup and the login tests. For the login tests I'd ask for a test environment where I control the second factor: a test user whose TOTP secret the tests know, so the test generates the code, or a test-only way to read the code. I wouldn't disable MFA for the login tests themselves, because that's the feature. For passkeys, Playwright 1.61+ has a virtual WebAuthn authenticator on the context, so the test can register and use a passkey without hardware."
Write a config with a setup project that signs in as ana and saves playwright/.auth/ana.json, and a test project that uses it. Then write a test that opens /practice/account directly and checks the "Display name" field shows "Ana", with no sign-in code in the test.
import{ test as setup, expect }from"@playwright/test";setup("sign in as ana",async({ page })=>{await page.goto("/practice/");await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();awaitexpect(page.getByText("Signed in as ana")).toBeVisible();await page.context().storageState({ path:"playwright/.auth/ana.json"});});
tests/account.spec.ts
import{ test, expect }from"@playwright/test";test("ana's display name defaults to Ana",async({ page })=>{await page.goto("/practice/account");awaitexpect(page.getByText("Signed in as ana")).toBeVisible();awaitexpect(page.getByLabel("Display name")).toHaveValue("Ana");});
npx playwright test
Running 2 tests using 1 worker
✓ 1 [setup] › tests/auth.setup.ts:3:1 › sign in as ana (1.0s)
✓ 2 [chromium] › tests/account.spec.ts:3:1 › ana's display name defaults to Ana (216ms)
2 passed (2.3s)
What’s happening
The setup project matches auth.setup.ts, signs in once, waits for the header, and saves the state. The chromium project depends on it and loads the file.
The test opens the account page directly. Without the saved state, the shop would redirect to sign-in; with it, the page loads signed in as ana.
The field's default is the user's name, "Ana". The test checks the header too, so a failure says clearly whether it was the session or the field.
Without clicking any "Add to cart" button, start a test signed in as rohit with three Wireless Mice in the cart, open the cart, press "−" once, and check the quantity is 2 and the total $59.00. Use page.localStorage (1.61+).
Show answer
tests/seed.spec.ts
import{ test, expect }from"@playwright/test";test("a seeded cart can be changed in the UI",async({ page })=>{await page.goto("/practice/");await page.localStorage.setItem("shop-user",JSON.stringify({ username:"rohit", name:"Rohit"}));await page.localStorage.setItem("shop-cart",JSON.stringify([{ id:"ms-01", name:"Wireless Mouse", price:29.5, qty:3}]));await page.goto("/practice/cart");awaitexpect(page.getByTestId("cart-total")).toHaveText("$88.50");await page.getByRole("button",{ name:"Decrease quantity of Wireless Mouse"}).click();awaitexpect(page.getByLabel("Quantity of Wireless Mouse",{ exact:true})).toHaveText("2");awaitexpect(page.getByTestId("cart-total")).toHaveText("$59.00");});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/seed.spec.ts:3:1 › a seeded cart can be changed in the UI (233ms)
1 passed (779ms)
What’s happening
The first goto puts the page on the shop's origin so it has a localStorage to write to.
Two setItem calls write a signed-in rohit and a cart line with qty: 3, in the shop's own format. The cart page shows $88.50 (3 × $29.50), which proves the seed worked before the test acts.
One click on "Decrease quantity of Wireless Mouse" takes it to 2, and the total to $59.00. exact: true keeps "Quantity of Wireless Mouse" from also matching the two buttons whose names contain it (Chapter 3).
This skips sign-in and four clicks. It's fine for arrange steps, as long as another test covers adding to the cart through the UI.
"How do you test error states in the UI, like the API returning a 500?"
Show answer
"I mock that one response with page.route: register the route before the action, fulfil with status: 500 (or abort the request for a network failure), and assert what the user sees: the error message, that nothing broke, that they can retry. I keep everything else real. For slow responses I hold the request in the route handler until the test releases it, so I can assert the loading state without guessing a delay. And I don't mock the happy path of our own API in E2E tests; that's covered by real calls, with API tests keeping the mocks honest."
"When would you write an API test instead of a UI test?"
Show answer
"Whenever the thing I'm checking is the API's behaviour: status codes, validation rules, permissions, response shape. API tests run in milliseconds, don't flake on rendering, and point straight at the endpoint that broke. The UI test should check that the UI uses the API correctly for the main journeys, not re-test every rule. I also use the API inside UI tests for setup and cleanup: creating the user or order the test needs is far faster and steadier through the API than through forms."
Write a test where the first products request fails with a 500 and the shop shows its error, and then, after a reload, the real catalogue loads. Use the times option of page.route so the mock only answers once.
Show answer
tests/recover.spec.ts
import{ test, expect }from"@playwright/test";test("after a failed load, a reload shows the products",async({ page })=>{await page.route("**/practice/api/products.json",(route)=> route.fulfill({ status:500}),{ times:1});await page.goto("/practice/");await page.localStorage.setItem("shop-user",JSON.stringify({ username:"ana", name:"Ana"}));await page.goto("/practice/shop");awaitexpect(page.getByRole("alert")).toHaveText("Couldn’t load products. Try again later.");await page.reload();awaitexpect(page.getByRole("listitem")).toHaveCount(8);awaitexpect(page.getByRole("alert")).toHaveCount(0);});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/recover.spec.ts:3:1 › after a failed load, a reload shows the products (1.8s)
1 passed (2.3s)
What’s happening
{ times: 1 } makes the route handle only the first matching request; after that it removes itself and requests go to the real server.
The first visit to the shop gets the 500, so the alert appears.
page.reload() requests the products again; the route is used up, so the real catalogue arrives and eight products show.
The last check makes sure the error is gone after recovery (no role="alert" left), which a test checking only the products would miss.
Write an API test (no browser) that checks GET /practice/api/promos/WELCOME5.json returns 200, JSON, and { code: "WELCOME5", percent: 5 }. Then write a UI test that types "welcome5" in lower case at the checkout and proves, by watching the network, that the shop requested WELCOME5.json, and that the summary shows the discount.
Show answer
tests/welcome5.spec.ts
import{ test, expect }from"@playwright/test";test("API: WELCOME5 gives 5% off",async({ request })=>{const res =await request.get("/practice/api/promos/WELCOME5.json");awaitexpect(res).toBeOK();expect(res.headers()["content-type"]).toBe("application/json");expect(await res.json()).toEqual({ code:"WELCOME5", percent:5});});test("UI: a lower-case code is sent in upper case and applied",async({ page })=>{await page.goto("/practice/");await page.localStorage.setItem("shop-user",JSON.stringify({ username:"ana", name:"Ana"}));await page.localStorage.setItem("shop-cart",JSON.stringify([{ id:"kb-01", name:"Mechanical Keyboard", price:89, qty:1}]));await page.goto("/practice/checkout");await page.getByLabel("Promo code").fill("welcome5");const requestPromise = page.waitForRequest("**/practice/api/promos/*.json");await page.getByRole("button",{ name:"Apply"}).click();const request =await requestPromise;expect(newURL(request.url()).pathname).toBe("/practice/api/promos/WELCOME5.json");awaitexpect(page.getByText("WELCOME5 applied: 5% off.")).toBeVisible();awaitexpect(page.getByTestId("order-total")).toHaveText("$84.55");});
npx playwright test
Running 2 tests using 1 worker
✓ 1 [chromium] › tests/welcome5.spec.ts:3:1 › API: WELCOME5 gives 5% off (25ms)
✓ 2 [chromium] › tests/welcome5.spec.ts:10:1 › UI: a lower-case code is sent in upper case and applied (296ms)
2 passed (914ms)
What’s happening
The API test checks status, content type and the exact body: everything the checkout reads from this endpoint, in milliseconds.
The UI test seeds ana with an $89 keyboard, types "welcome5", and starts waitForRequestbefore clicking Apply, so the request can't slip past.
The request's path is /practice/api/promos/WELCOME5.json: the front end upper-cased the code (code.trim().toUpperCase() in the shop's script) before asking the server.
The summary shows the result: $89.00 − 5% ($4.45) = $84.55. The two tests check different halves of one feature (the server's answer, and the UI's use of it), which is how API and UI tests should split the work.
"How do you do visual regression testing with Playwright, and how do you stop it being flaky?"
Show answer
"expect(page or locator).toHaveScreenshot() compares against a baseline committed next to the test. The first run writes the baseline and fails on purpose; --update-snapshots approves intentional changes, and the new images are reviewed in the pull request like code. To keep it reliable I screenshot small, meaningful elements rather than whole pages, mask the parts that legitimately change (user names, dates, ads), fix the clock and time zone, keep animations disabled (the default), and generate baselines in the same Docker image CI uses, because fonts and rendering differ between macOS and Linux. I keep tolerances small: a pixel budget for anti-aliasing noise, never a large ratio that would hide a real change."
"When would you use toMatchAriaSnapshot instead of a screenshot or individual assertions?"
Show answer
"When I care about the structure and content of a block, not its pixels: a navigation menu, a form, a product card, a results table. One aria snapshot checks roles, names and states for the whole block, it ignores fonts and rendering so it doesn't flake across machines, and its diff says in words what changed. Templates are partial and accept regexes, so I list only what matters. I'd use a screenshot when the look itself is the requirement, and individual toHaveText-style assertions for the one or two facts a behaviour test is about. It also nudges the team towards accessible markup, because an element with no role or name shows up badly in the snapshot."
"How do you test accessibility in your E2E suite, and what are the limits?"
Show answer
"I run axe through @axe-core/playwright on each important page and state (the form with errors, the open dialog), with the WCAG A and AA tags, and assert on a fingerprint of the violations so failures are readable. It catches missing labels and names, contrast, invalid ARIA and similar rule-based problems. It can't tell whether a label is true, whether focus order and keyboard flow make sense, or whether a screen-reader user can actually complete the journey, so we keep role-based locators in every functional test, add a few keyboard-only tests for critical flows, and do manual checks. I also read axe's incomplete list: that's where it says a human must decide."
Your turn: a visual test of the cart that works for any user
Write a visual test of the cart table with two products in it. Sign in as Rohit for the baseline, and make sure the same test signed in as Ana compares against the same baseline and passes. Don't screenshot the whole page.
Show answer
tests/cart-visual.spec.ts
import{ test, expect,typePage}from"@playwright/test";asyncfunctioncartWithTwoProducts(page: Page, username:string){await page.goto("/practice/");await page.getByLabel("Username").fill(username);await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();for(const name of["Compact Keyboard","Monitor Light Bar"]){await page.getByRole("listitem").filter({ hasText: name }).getByRole("button",{ name:"Add to cart"}).click();}await page.getByRole("link",{ name:"Cart (2)"}).click();awaitexpect(page.getByTestId("cart-total")).toHaveText("$108.00");}for(const username of["rohit","ana"]){test(`the cart table looks right for ${username}`,async({ page })=>{awaitcartWithTwoProducts(page, username);awaitexpect(page.getByRole("table",{ name:"Your cart"})).toHaveScreenshot("cart-table.png");});}
npx playwright test --update-snapshots --grep rohit
Running 1 test using 1 worker
A snapshot doesn't exist at <project>/tests/cart-visual.spec.ts-snapshots/cart-table-chromium-darwin.png, writing actual.
✓ 1 [chromium] › tests/cart-visual.spec.ts:16:3 › the cart table looks right for rohit (1.8s)
1 passed (2.3s)
npx playwright test
Running 2 tests using 1 worker
✓ 1 [chromium] › tests/cart-visual.spec.ts:16:3 › the cart table looks right for rohit (1.6s)
✓ 2 [chromium] › tests/cart-visual.spec.ts:16:3 › the cart table looks right for ana (1.6s)
2 passed (3.5s)
What’s happening
The arrange helper adds two products and waits for the total ($59.00 + $49.00 = $108.00), so the screenshot is never taken of a half-rendered table.
The screenshot is of the table only. The user's name lives in the header, outside the table, so there's nothing to mask: choosing a tight element is often better than masking.
Both tests use the name cart-table.png, so they share one baseline: the --grep rohit update makes it from Rohit's cart, and the normal run checks both users against it. Both pass because the table doesn't depend on who's signed in.
If you had screenshotted the whole page, Ana's run would fail on "Signed in as ana", and you'd need a mask over the name, plus a fixed-width box for it, as in the masking example.
Your turn: pin down the checkout's error state with an aria snapshot
Submit the checkout with the name cleared and nothing else filled in, then check the error summary and the four field errors with onetoMatchAriaSnapshot on the form. Keep the template partial: only what proves the errors are shown.
Show answer
tests/checkout-errors.spec.ts
import{ test, expect }from"@playwright/test";test("an empty checkout shows every error",async({ page })=>{await page.goto("/practice/");await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();await page.getByRole("listitem").filter({ hasText:"USB Microphone"}).getByRole("button",{ name:"Add to cart"}).click();await page.goto("/practice/checkout");await page.getByLabel("Full name").clear();await page.getByRole("button",{ name:"Place order"}).click();awaitexpect(page.locator("#checkout")).toMatchAriaSnapshot(`
- alert: Please fix 4 problems before placing your order.
- textbox "Full name"
- paragraph: Enter your full name.
- textbox "Email"
- paragraph: Enter your email.
- textbox "Delivery address"
- paragraph: Enter your full delivery address.
- checkbox "I agree to the terms"
- paragraph: You must agree to the terms.
- button "Place order"
`);});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/checkout-errors.spec.ts:3:1 › an empty checkout shows every error (1.5s)
1 passed (2.0s)
What’s happening
Clearing "Full name" (the shop pre-fills it) and submitting triggers all four validation rules, so the alert reads "Please fix 4 problems before placing your order."
The template lists the alert first, then each field followed by its error paragraph, then the button, in page order. Order is checked, so this also proves each error sits right after its own field.
It's partial: the labels' text nodes, the promo code box, the delivery radios and the payment note are all left out, and the match still passes because the default mode is contain.
page.locator("#checkout") scopes it to the form. (A form only gets the form role when it has an accessible name, so a role locator wouldn't find this one; the id is the honest choice here.) Compared with nine separate assertions, the template reads like the screen and fails with a diff that shows which error went missing.
Write a test that places an order and runs axe with the WCAG A and AA tags on the confirmation page, attaching the full results to the report and asserting on a fingerprint of the violations.
Show answer
tests/confirmation-a11y.spec.ts
import{ test, expect }from"@playwright/test";import AxeBuilder from"@axe-core/playwright";test("the order confirmation has no WCAG A/AA violations",async({ page }, testInfo)=>{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("listitem").filter({ hasText:"Standing Desk Mat"}).getByRole("button",{ name:"Add to cart"}).click();await page.goto("/practice/checkout");await page.getByLabel("Email").fill("rohit@example.com");await page.getByLabel("Delivery address").fill("12 Long Street, Toronto");await page.getByLabel("I agree to the terms").check();await page.getByRole("button",{ name:"Place order"}).click();awaitexpect(page.getByRole("heading",{ name:"Thank you, Rohit!"})).toBeVisible();const results =awaitnewAxeBuilder({ page }).withTags(["wcag2a","wcag2aa","wcag21a","wcag21aa"]).analyze();await testInfo.attach("accessibility-scan-results",{ body:JSON.stringify(results,null,2), contentType:"application/json"});expect(results.violations.map((v)=>({ rule: v.id, targets: v.nodes.map((n)=> n.target.join(" "))}))).toEqual([]);console.log(`rules passed: ${results.passes.length}, violations: ${results.violations.length}`);});
npx playwright test
Running 1 test using 1 worker
rules passed: 10, violations: 0
✓ 1 [chromium] › tests/confirmation-a11y.spec.ts:4:1 › the order confirmation has no WCAG A/AA violations (3.1s)
1 passed (3.6s)
What’s happening
The test places a real order and waits for the thank-you heading, so axe scans the finished confirmation, not the "Placing order…" moment.
testInfo.attach puts the whole result (passes, violations, incomplete) into the HTML report, so whoever investigates a failure on CI sees everything axe saw.
The assertion uses the rule-and-selector fingerprint, so a failure prints a short, stable diff.
The printed line shows how many rules passed and that there were 0 violations. As before, that means nothing axe can detect is wrong; it doesn't prove a screen-reader user can read the confirmation comfortably.
"A test fails on CI but passes locally. How do you debug it?"
Show answer
"First the error message and the error context the report gives me: which assertion, what it expected and received, and the page's state. Then the trace: our config records one on the first retry, so I open it from the HTML report and step through the actions, looking at the DOM snapshot before and after the failing step, the network requests and the console. That usually shows the cause directly: a click that landed on the wrong element, a response that came back slower or with different data, an error in the console. If it's a timing problem, I reproduce it locally with --repeat-each and CPU throttling or more workers rather than guessing, fix the cause (a missing wait on the right condition, shared data), and never just add a sleep or a retry."
"I treat a flake as a bug with a cause, usually a race, shared data, order dependence, time, or the environment. CI runs with retries and traces on the first retry, so a flake shows up as 'flaky' in the report with a recording of the failing attempt rather than silently passing. I reproduce with --repeat-each and more workers, fix the cause (wait for the right condition, isolate the data, control the clock), and verify with a few hundred repeats. If it can't be fixed right away it goes into quarantine: a tag excluded from the blocking job, a ticket and an owner, still run nightly. We track the flaky rate, and on main we can turn on failOnFlakyTests so new flakes can't sneak in. What I never do is add a sleep or raise a timeout without understanding why."
"How would you test a session timeout of 30 minutes, or a date that depends on today?"
Show answer
"With Playwright's clock API. For the timeout, I'd page.clock.install() before loading the app, sign in, then fastForward('30:00') and assert the 'You've been logged out' message, so the test takes a second, not half an hour. If I need the exact boundary I'd pauseAt a moment and runFor up to one millisecond before and after. For dates, setFixedTime to a fixed moment, often a nasty one like 31 December or a daylight-saving change, plus a fixed timezoneId, so the expected date is a constant in the test rather than computed from Date.now(), which would just repeat the app's logic. The one caveat is that it only fakes browser time; anything time-based on the server needs its own control."
This test fails. Without running anything else, use the error to say why, then fix it so it tests what its title says.
TypeScript
test("ana can add the compact keyboard",async({ page })=>{await page.goto("/practice/");await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();await page.getByRole("button",{ name:"Add to cart"}).click();awaitexpect(page.getByRole("link",{ name:"Cart (1)"})).toBeVisible();});
Show answer
Here's the run of that test, then the fixed test:
tests/keyboard.spec.ts
import{ test, expect }from"@playwright/test";test("as written: ana can add the compact keyboard",async({ page })=>{await page.goto("/practice/");await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();await page.getByRole("button",{ name:"Add to cart"}).click({ timeout:3000});awaitexpect(page.getByRole("link",{ name:"Cart (1)"})).toBeVisible();});test("fixed: ana can add the compact keyboard",async({ page })=>{await page.goto("/practice/");await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();await page.getByRole("listitem").filter({ hasText:"Compact Keyboard"}).getByRole("button",{ name:"Add to cart"}).click();awaitexpect(page.getByRole("link",{ name:"Cart (1)"})).toBeVisible();awaitexpect(page.getByRole("status").filter({ hasText:"Added"})).toHaveText("Added Compact Keyboard to your cart");});
npx playwright test
Running 2 tests using 1 worker
✘ 1 [chromium] › tests/keyboard.spec.ts:3:1 › as written: ana can add the compact keyboard (1.5s)
✓ 2 [chromium] › tests/keyboard.spec.ts:12:1 › fixed: ana can add the compact keyboard (1.5s)
1) [chromium] › tests/keyboard.spec.ts:3:1 › as written: ana can add the compact keyboard ────────
Error: locator.click: Error: strict mode violation: getByRole('button', { name: 'Add to cart' }) resolved to 8 elements:
1) <button type="button" data-add="kb-01">Add to cart</button> aka getByTestId('product-kb-01').getByRole('button', { name: 'Add to cart' })
2) <button type="button" data-add="kb-02">Add to cart</button> aka getByTestId('product-kb-02').getByRole('button', { name: 'Add to cart' })
3) <button type="button" data-add="ms-01">Add to cart</button> aka getByTestId('product-ms-01').getByRole('button', { name: 'Add to cart' })
4) <button disabled type="button">Add to cart</button> aka getByTestId('product-ms-02').getByRole('button', { name: 'Add to cart' })
5) <button type="button" data-add="au-01">Add to cart</button> aka getByTestId('product-au-01').getByRole('button', { name: 'Add to cart' })
6) <button type="button" data-add="au-02">Add to cart</button> aka getByTestId('product-au-02').getByRole('button', { name: 'Add to cart' })
7) <button type="button" data-add="dk-01">Add to cart</button> aka locator('li:nth-child(7) > button')
8) <button type="button" data-add="dk-02">Add to cart</button> aka locator('li:nth-child(8) > button')
Call log:
- waiting for getByRole('button', { name: 'Add to cart' })
6 | await page.getByLabel("Password").fill("playwright");
7 | await page.getByRole("button", { name: "Sign in" }).click();
> 8 | await page.getByRole("button", { name: "Add to cart" }).click({ timeout: 3000 });
| ^
9 | await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
10 | });
11 |
at <project>/tests/keyboard.spec.ts:8:59
Error Context: test-results/keyboard-as-written-ana-can-add-the-compact-keyboard-chromium/error-context.md
1 failed
[chromium] › tests/keyboard.spec.ts:3:1 › as written: ana can add the compact keyboard ─────────
1 passed (3.8s)
What’s happening
The error is a strict mode violation: getByRole('button', { name: 'Add to cart' }) resolved to 8 elements, one per product, and the call log lists them. Playwright refuses to guess which one you meant (Chapter 4).
The title says "compact keyboard", but the locator never mentions it: the test was written as if there were one product. The fix scopes the locator to the card that contains "Compact Keyboard", then finds its button.
The fixed test also checks the message names the right product. "Cart (1)" alone would pass if any product were added, which is exactly how the .first() bug in the Trace Viewer example slipped through.
Don't fix a strict mode violation with .first() or .nth(1). It makes the error go away by picking an element by position, which breaks as soon as the order changes.
Your turn: test the 3-second message without waiting 3 seconds
Write a test that adds a product and checks the "Added" message is gone after 3 seconds, using the clock so the test doesn't wait in real time. Use fastForward this time.
Running 1 test using 1 worker
✓ 1 [chromium] › tests/toast-clock.spec.ts:3:1 › the added message is cleared after 3 seconds (1.5s)
1 passed (2.0s)
What’s happening
page.clock.install() with no time starts the fake clock at the current time, before the page loads. Time still flows, so sign-in and the product load work normally.
After the click, the message is visible and its 3-second timer is waiting on the fake clock.
fastForward("03") jumps the clock 3 seconds ahead and fires the due timer once (the string format is seconds, "01:00" would be a minute). The message is cleared immediately.
toBeHidden({ timeout: 500 }) proves it disappeared because of the jump, not because 3 real seconds passed: half a second wouldn't be enough for the real timer. The cart count shows the product is still in the cart; only the message went.
The difference from runFor: fastForward skips straight to the end and fires due timers once, like waking a sleeping laptop; runFor plays every timer on the way. For "is it gone after N seconds" either works; for an interval that should tick several times, use runFor.
"How does Playwright run tests in parallel, and how do you keep parallel tests from interfering?"
Show answer
"Playwright starts several worker processes, each with its own browser. Files run in parallel by default and tests inside a file run in order; fullyParallel spreads individual tests across workers too, which I turn on because it also exposes hidden dependencies. Each test gets a fresh browser context, and a worker is replaced after a failure, so browser state can't leak. What can still collide is backend data, so every test creates its own data or uses a per-worker account named after parallelIndex. For the rare resource that truly can't be shared, Playwright 1.63+ has test locks, so only those tests serialise. On CI I size workers to the runner, and I use sharding when one machine isn't enough."
"Your E2E suite takes 45 minutes and the team has stopped trusting it. What do you do?"
Show answer
"First measure: which tests are slow, which are flaky, and what the suite actually covers, using the HTML report's timings and the JSON results over a few weeks of runs. Then fix the shape before buying hardware: push validation and edge cases down to unit and API tests, keep E2E for the critical journeys, and stop doing setup through the UI: a saved session instead of logging in each time, test data created through the API. Then run it properly: fullyParallel, independent tests, workers sized to the runner, shards with merged reports. Split the pipeline into a smoke set on every pull request and the full cross-browser run on main and nightly. Flaky tests get fixed or quarantined with an owner, and failOnFlakyTests keeps new ones out. The goal is a PR signal in about 10 minutes that people believe."
Split this chapter's six shop and sign-in tests into three shards with the blob reporter, collect the blobs, and merge them into one list report. Predict how many tests each shard runs before you look.
import{ test, expect }from"@playwright/test";
test.beforeEach(async({ page })=>{await page.goto("/practice/");await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();});test("shows eight products",async({ page })=>{awaitexpect(page.getByRole("listitem")).toHaveCount(8);});test("search finds the wireless mouse",async({ page })=>{await page.getByLabel("Search products").fill("wireless");awaitexpect(page.getByRole("listitem")).toHaveText([/Wireless Mouse/]);});test("the category filter shows only audio",async({ page })=>{await page.getByLabel("Category").selectOption("Audio");awaitexpect(page.getByRole("listitem")).toHaveCount(2);});test("the sold-out product can't be added",async({ page })=>{awaitexpect(page.getByRole("listitem").filter({ hasText:"Vertical Mouse"}).getByRole("button")).toBeDisabled();});test("adding a product updates the cart count",async({ page })=>{await page.getByRole("listitem").filter({ hasText:"USB Microphone"}).getByRole("button",{ name:"Add to cart"}).click();awaitexpect(page.getByRole("link",{ name:"Cart (1)"})).toBeVisible();});test("signing out returns to the sign-in page",async({ page })=>{await page.getByRole("button",{ name:"Log out"}).click();awaitexpect(page.getByRole("heading",{ name:"Sign in"})).toBeVisible();});
collect-blob.mjs
// Stands in for CI's upload-artifact + download-artifact steps: gathers each shard's blob report into one folder.import{ cpSync, mkdirSync, readdirSync }from"node:fs";mkdirSync("all-blob-reports",{recursive:true});for(const f ofreaddirSync("blob-report")){cpSync(`blob-report/${f}`,`all-blob-reports/${f}`);
console.log(`blob-report/${f} → all-blob-reports/${f}`);}
npx playwright test --shard=1/3
Running 2 tests using 2 workers, shard 1 of 3
··
2 passed (2.4s)
Running 6 tests using 6 workers
✓ 1 [chromium] › tests/shop.spec.ts:10:1 › shows eight products (1.5s)
✓ 2 [chromium] › tests/shop.spec.ts:13:1 › search finds the wireless mouse (1.8s)
✓ 4 [chromium] › tests/shop.spec.ts:21:1 › the sold-out product can't be added (1.5s)
✓ 3 [chromium] › tests/shop.spec.ts:17:1 › the category filter shows only audio (1.7s)
✓ 5 [chromium] › tests/shop.spec.ts:28:1 › signing out returns to the sign-in page (1.0s)
✓ 6 [chromium] › tests/shop.spec.ts:24:1 › adding a product updates the cart count (1.5s)
6 passed (6.8s)
What’s happening
Six tests, fullyParallel, three shards: two tests per shard, because sharding at test level divides them evenly. Without fullyParallel all six would be one file, and shard 1 would get the whole file while shards 2 and 3 got nothing (and, since 1.65, an empty shard set fails with "No tests found" unless you pass --pass-with-no-tests).
Each shard uses the dot reporter for its own log and the blob reporter for the merge: two dots per shard, and report-1.zip, report-2.zip, report-3.zip.
The collect step puts the three zips side by side, as the merge job's download step would.
merge-reports --reporter=list prints all six tests as one run. With --reporter=html you'd get one browsable report for the whole suite, which is what you'd upload from CI.
Your turn: a smoke workflow for pull requests and a full nightly run
Write a workflow that runs only @smoke tests in Chromium on every pull request, and the full suite in all browser projects every night at 03:00 UTC. It must pass actionlint.
Two triggers: pull_request for every PR to main, and schedule with the cron expression 0 3 * * * (minute 0, hour 3, every day; GitHub's schedule times are UTC).
Each job has an if on github.event_name, so a PR runs only smoke and the nightly run only full.
Smoke installs only Chromium and runs --project=chromium --grep @smoke: the handful of tagged tests, minutes not hours.
Full uses a matrix over the three browser projects (this assumes projects named chromium, firefox and webkit in the config, as in Chapter 2), installs only the browser each copy needs, and keeps every report, with fail-fast: false so one browser's failure doesn't cancel the others. To shard each browser too, add a shardIndex dimension and the blob/merge steps from the main workflow.
It passes actionlint (the site's checker runs it on every block like this); it wasn't run on GitHub.
This page has a "Place order" <div> with a click handler and cursor: pointer, a real "Place order" <button>, an icon button with aria-label="Close", and an <img> with no alt. What does the agent see, and how many buttons named "Place order" does getByRole find?
Running 1 test using 1 worker
- generic [active] [ref=e1]:
- generic [ref=e2] [cursor=pointer]: Place order
- button "Place order" [ref=e3]
- button "Close" [ref=e4]
✓ 1 [chromium] › tests/fake-button.spec.ts:3:1 › what an agent sees of two 'buttons' (84ms)
1 passed (529ms)
What’s happening
The <div> is just generic … [cursor=pointer]: Place order. Nothing says it's a button; the only clue is the pointer cursor, which the AI mode adds as a hint. A model may or may not guess it's clickable, and a screen reader user gets no hint at all.
The real <button> is button "Place order": role and name, unmistakable. getByRole("button", { name: "Place order" }) finds exactly 1, the real one.
The icon button has no text, but aria-label="Close" gives it a name, so it appears as button "Close". Without the label it would be a nameless button that no agent (or test, or person) could pick out.
The <img> without alt doesn't appear at all.
The lesson for a team: an app that's accessible is an app agents (and getByRole tests) can use. Fixing roles and labels helps users, tests and agents at once.
"Why do AI browser agents read the accessibility tree instead of screenshots?"
Show answer
"Because it's the page's meaning as compact text: each control's role, name and state, with an id the model can point at. That's much smaller than an image, it gives exact names instead of a guess from pixels, and an action on a ref can't miss the way a coordinate click can. Playwright MCP works this way by default, and Playwright's actions still auto-wait, so the agent gets reliable clicks. Screenshots are still useful for visual questions, and there's an opt-in vision mode with coordinate tools for things the tree doesn't expose, like a canvas. The catch is that it depends on accessibility: a div with a click handler and no role is nearly invisible to an agent."
"What is Playwright MCP, and how is it different from writing Playwright tests?"
Show answer
"It's an MCP server that exposes Playwright's browser control as tools a model can call: navigate, snapshot, click, type, fill a form, and so on. The model sees the page as an accessibility snapshot with refs and picks one tool call at a time. A test is code you wrote and review, deterministic and cheap to rerun; an MCP session is the model deciding at run time, so it's slower, costs tokens and can do something different each time. I use MCP for exploring an app, reproducing a bug, or letting an agent draft a test, and every action answer includes the Playwright code it ran, so the output can become a real test. It doesn't replace the suite in CI: that stays deterministic code."
"Have you used Playwright's test agents? What are they good and bad at?"
Show answer
"They're three agent definitions Playwright generates with npx playwright init-agents: a planner that explores the app and writes a Markdown test plan, a generator that performs each step live and writes the test, and a healer that runs failing tests, debugs them and edits them. They're good at the slow parts: exploring a feature, drafting a plan, producing a first version of a test with decent role-based locators, and fixing a locator after a UI change. They're weak at judgement: the generated assertions can be too broad, like checking that 'Sold out' appears anywhere on the page, and the healer is told to make tests pass, so its last resort is marking a test fixme, which can hide a real bug. So I'd treat them as a fast junior: review the plan before generating, review every test and every healer diff like a normal PR, and treat any new fixme as a possible bug."
"How do you make sure tests written by AI are trustworthy?"
Show answer
"I treat them like a pull request from a new teammate: they're a draft until reviewed. First, does it fail when the feature breaks? I break the feature on purpose, by mocking a response or editing the app locally, and the test must go red. Then the usual review: assertions on the outcome the user sees rather than a success message, web-first assertions with no sleeps, role-based locators scoped to the right element, no conditional or swallowed assertions, its own data so it runs alone, and our fixtures and page objects rather than copied login code. And I watch for agents 'fixing' tests by skipping them or loosening assertions. Giving the assistant a good seed test, our fixtures and an example test to imitate makes the first draft much better."
An assistant wrote this for "test that removing an item updates the cart". It passes (the run is below it). List what's wrong with it, then rewrite it so it would fail if removing didn't work.
Running 1 test using 1 worker
✓ 1 [chromium] › tests/remove.spec.ts:3:1 › should remove item (2.9s)
1 passed (3.5s)
Show answer
The problems: page.fill / page.click with CSS selectors (the old page-level API; locators are the recommended way), two fixed sleeps, products chosen by position, button:has-text('Remove') clicks whichever Remove button comes first, and the assertion rows > 0 is true before the click too, so it can't fail if Remove does nothing. (A first draft of this exercise used text=Sign in and text=Remove, and it hung: text=Sign in matched the "Sign in" heading before the button, and text=Remove matched the cart table's hidden "Remove" column header, which can never become clickable. Loose text selectors pick the first match in the page, whatever it is.) A version that tests the behaviour:
tests/remove.spec.ts
import{ test, expect }from"@playwright/test";test("removing one product leaves the other and updates the total",async({ page })=>{await page.goto("/practice/");await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();for(const name of["Mechanical Keyboard","Compact Keyboard"]){await page.getByRole("listitem").filter({ hasText: name }).getByRole("button",{ name:"Add to cart"}).click();}await page.getByRole("link",{ name:"Cart (2)"}).click();awaitexpect(page.getByTestId("cart-total")).toHaveText("$148.00");await page.getByRole("button",{ name:"Remove Mechanical Keyboard"}).click();awaitexpect(page.getByRole("row",{ name:/Mechanical Keyboard/})).toHaveCount(0);awaitexpect(page.getByRole("row",{ name:/Compact Keyboard/})).toBeVisible();awaitexpect(page.getByTestId("cart-total")).toHaveText("$59.00");awaitexpect(page.getByRole("link",{ name:"Cart (1)"})).toBeVisible();});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/remove.spec.ts:3:1 › removing one product leaves the other and updates the total (1.7s)
1 passed (2.2s)
What’s happening
The products are chosen by name, not position, and the cart is opened through the header link "Cart (2)", which also proves both were saved.
The total is checked before removing ($89.00 + $59.00 = $148.00), so the test knows its starting point.
The button is named for the product it removes ("Remove Mechanical Keyboard"), so there's no doubt which row goes.
Four facts prove the removal: the keyboard's row is gone (toHaveCount(0) retries until it is), the other row is still there, the total dropped to $59.00, and the header says "Cart (1)". The original's rows > 0 was true before and after the click.
No sleeps: every assertion waits for its own condition.
Register a WebMCP tool get_cart_count on the shop (no input; returns the number in the header's "Cart (n)" link as a number) with an init script, then test that it returns 0 before and 2 after adding two products through the UI.
import{ test, expect }from"@playwright/test";test("get_cart_count follows the cart",async({ page })=>{await page.addInitScript(()=>{(document asany).modelContext.registerTool({
name:"get_cart_count",
description:"How many items are in the cart.",
annotations:{ readOnlyHint:true},execute:async()=>Number(document.querySelector("[data-cart-link]")?.textContent?.match(/\d+/)?.[0]??0),});});await page.goto("/practice/");await page.getByLabel("Username").fill("rohit");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();awaitexpect(page.getByRole("listitem")).toHaveCount(8);expect(await page.webmcp.callTool("get_cart_count")).toBe(0);await page.getByRole("listitem").filter({ hasText:"USB Microphone"}).getByRole("button",{ name:"Add to cart"}).click();await page.getByRole("listitem").filter({ hasText:"USB Microphone"}).getByRole("button",{ name:"Add to cart"}).click();await expect.poll(()=> page.webmcp.callTool("get_cart_count")).toBe(2);awaitexpect(page.getByRole("link",{ name:"Cart (2)"})).toBeVisible();});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/cart-count-tool.spec.ts:3:1 › get_cart_count follows the cart (1.6s)
1 passed (2.1s)
What’s happening
The init script runs before the shop's own script on every page of the test, so the tool exists on the shop page after sign-in. It has no input schema because it takes no input; callTool defaults the input to {}.
The test waits for the 8 products before calling the tool, so the header (and its cart link) has been drawn.
The first call returns 0, a number, because execute returned one; WebMCP results don't have to be strings.
After two clicks, the test uses expect.poll (Chapter 6) to call the tool again until it returns 2: the tool reads the page, so like any check on the page it should retry rather than read once.
The last line checks the same fact through the UI. If the tool and the page ever disagree, one of them has a bug, and this test would say so.
Using page.ariaSnapshot({ mode: "ai" }) and page.getByRef(), sign in as Ana without writing a single role or label locator for the form: find each ref in the snapshot text. Then assert, normally, that you're signed in.
Show answer
tests/refs.spec.ts
import{ test, expect }from"@playwright/test";test("sign in by refs, like an agent",async({ page })=>{await page.goto("/practice/");const snapshot =await page.ariaSnapshot({ mode:"ai"});constref=(line:string)=> snapshot.match(newRegExp(`${line} \\[ref=(\\w+)\\]`))![1];await page.getByRef(ref('textbox "Username"')).fill("ana");await page.getByRef(ref('textbox "Password"')).fill("playwright");await page.getByRef(ref('button "Sign in"')).click();awaitexpect(page.getByText("Signed in as ana")).toBeVisible();});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/refs.spec.ts:3:1 › sign in by refs, like an agent (967ms)
1 passed (1.4s)
What’s happening
The snapshot is plain text, so finding a ref is a text search: the line for the Username box reads textbox "Username" [ref=e10], and the regular expression captures e10.
getByRef turns each ref into a locator for that element. The refs belong to the snapshot just taken, which is why the test snapshots once and uses all three refs before the page changes.
The click signs in and the page navigates; the old refs now mean nothing, exactly as for an agent, which would snapshot again on the new page.
The final check is an ordinary assertion on what the user sees. In a real suite you'd write the form steps with getByLabel too: refs exist for agents, and a test that depends on ref numbers breaks whenever the page gains an element.
"I start from the journeys, rank them by how often they're used and what a break costs, and give each critical one a small number of E2E tests: the happy path, the rules that involve money or security, and the failures a user will actually hit. Everything with many inputs, like validation rules or pricing maths, goes to unit and API tests. I tag one test per journey as smoke so there's a fast check for every push and for production after a deploy. And I write the plan down as a table with a 'left to cheaper tests' column, because the decisions not to test something end to end are as important as the tests."
"For a shop app, I built a Playwright suite around the five journeys that matter: sign-in, search, cart, checkout and account, about twenty tests, picked by risk, with one smoke test per journey. A setup project signs in once and saves the session, so only the login tests use the form. Tests use fixtures that hand them page objects and set up data directly, so a test reads as 'with this cart, apply SAVE10, the total is $80.10'. Everything runs fully parallel in Chromium, Firefox and WebKit in about half a minute, because each test makes its own data and there are no sleeps. In CI it's sharded four ways with blob reports merged into one HTML report, traces on retry and annotations on the PR. The parts I'd point to as decisions are arranging state directly instead of through the UI, mocking only what we can't make happen, and keeping the validation rules in unit tests."
"How do you keep an E2E suite from becoming slow and flaky as it grows?"
Show answer
"Three habits. First, a budget: every new E2E test has to justify itself against a cheaper test, and the plan has a 'left to cheaper tests' column. Second, isolation: each test creates its own data and never depends on another test, which is what makes full parallelism and sharding safe. Third, treating flakiness as a bug with an owner: retries are on in CI so one flake doesn't block a merge, but the report marks flaky tests, and anything flaky gets fixed or quarantined within days, not left to rot. On the speed side, sharding with merged reports, smoke tests first, and fewer browsers on pull requests than on main."
"Why page objects and fixtures, and not just helper functions?"
Show answer
"Page objects give one place for a page's locators, so a UI change is one edit, and they make tests read in the user's language. Fixtures are Playwright's way of providing things to tests with setup and teardown, so instead of every test constructing page objects and seeding data, it just asks for cart or cartWith, and Playwright builds only what that test uses. Helpers are fine for pure logic. I avoid page objects that assert, and giant base classes; small objects composed together age better."
The suite signs in as Rohit once, in the setup project. Add a fixture signedInAs(username, name) that starts a test signed in as anyone without using the form or a setup project, by writing the shop's shop-user entry before the page loads. Use it to check that Ana's account page shows "Signed in as ana", "Ana" as the display name, and "No orders yet.".
Show answer
tests/fixtures.ts
import{ test as base }from"@playwright/test";exportconst test = base.extend<{signedInAs:(username:string, name:string)=>Promise<void>}>({signedInAs:async({ page }, use)=>{awaituse(async(username, name)=>{// Runs in every page of this test before the shop's own script, so the shop always finds a signed-in user.await page.addInitScript((user)=> localStorage.setItem("shop-user",JSON.stringify(user)),{ username, name });});},});export{ expect }from"@playwright/test";
tests/account.spec.ts
import{ test, expect }from"./fixtures";test("Ana's account starts with no orders",async({ page, signedInAs })=>{awaitsignedInAs("ana","Ana");await page.goto("/practice/account");awaitexpect(page.getByText("Signed in as ana")).toBeVisible();awaitexpect(page.getByLabel("Display name")).toHaveValue("Ana");awaitexpect(page.getByText("No orders yet.")).toBeVisible();awaitexpect(page.getByRole("button",{ name:"Download orders (CSV)"})).toBeDisabled();});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/account.spec.ts:3:1 › Ana's account starts with no orders (152ms)
1 passed (714ms)
What’s happening
page.addInitScript registers a script that runs in every page of this test, before the page's own scripts. It writes {"username":"ana","name":"Ana"} to shop-user, so when the account page's script calls requireUser(), Ana is already signed in.
The test goes straight to /practice/account: no form, no redirect, no 0.5 s sign-in delay.
Four checks: the header names Ana, the display name defaults to her name, the order history is empty, and the download button is disabled because there's nothing to download.
The trade-off: this is faster than a setup project, but it relies on how the shop stores its session (the key and the JSON shape). If the shop changed that, these tests would keep passing a login that real users can't do. The setup project signs in through the real form, so it fails when login breaks. Use the shortcut for extra users and roles, and keep at least one real sign-in in the run.
Add a phone project to a config so that phones run only the @smoke tests, while desktop Chromium runs everything. Prove it with a run of one smoke test and one other test.
Show answer
playwright.config.ts
import{ defineConfig, devices }from"@playwright/test";exportdefaultdefineConfig({
testDir:"./tests",
fullyParallel:true,
use:{ baseURL:"https://rohit-playwright.pages.dev"},
projects:[{ name:"chromium", use:{...devices["Desktop Chrome"]}},// Phones get the smoke tests only: the journeys that must work everywhere, at a fraction of the cost.{ name:"phone", use:{...devices["Pixel 10"]}, grep:/@smoke/},],});
tests/shop.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("search finds products by name",{ tag:"@smoke"},async({ page })=>{await page.getByLabel("Search products").fill("keyboard");awaitexpect(page.getByRole("list",{ name:"Products"}).getByRole("listitem")).toHaveCount(2);});test("sorting by price puts the cheapest first",async({ page })=>{await page.getByLabel("Sort by").selectOption("Price: low to high");awaitexpect(page.getByRole("list",{ name:"Products"}).getByRole("heading").first()).toHaveText("Wireless Mouse");});
npx playwright test
Running 3 tests using 3 workers
✓ 3 [phone] › tests/shop.spec.ts:10:1 › search finds products by name @smoke (1.8s)
✓ 2 [chromium] › tests/shop.spec.ts:10:1 › search finds products by name @smoke (1.8s)
✓ 1 [chromium] › tests/shop.spec.ts:15:1 › sorting by price puts the cheapest first (1.9s)
3 passed (2.5s)
What’s happening
grep works on a project as well as on the command line: the phone project only runs tests whose title or tags match /@smoke/.
So the run has 3 tests, not 4: both tests in chromium, and only the search test in phone. The sorting test never runs on the phone.
devices["Pixel 10"] gives the phone project Chromium with a 360 px wide viewport, touch and a mobile user agent (Chapter 2). The shop's layout stacks at that width, and the role and label locators don't care.
This is how teams keep device coverage affordable: the full suite on one desktop browser, a small smoke set on every device class. grepInvert on a project does the opposite (everything except a tag).
"Walk me through what happens when you run npx playwright test."
Show answer
"Playwright loads the config, finds the test files under testDir, and works out the list of tests per project, so with three browser projects every test is listed three times. Projects with dependencies, like a setup project that signs in, are scheduled first. Then it starts worker processes, half the CPU cores by default, and hands them tests: whole files by default, individual tests with fullyParallel. Each worker launches a browser once and gives every test a fresh browser context, which is a clean profile: no cookies, no storage. Fixtures are set up for each test as it asks for them and torn down after, in reverse order, even if the test failed. Results stream to the reporters, and a worker that hits a failure is thrown away and replaced so no broken state leaks into the next test. With retries on, a failed test is re-run in a fresh worker, and if it then passes it's reported as flaky."
"What's the difference between a browser, a context and a page, and why does it matter for tests?"
Show answer
"A browser is the process, expensive to start, so Playwright launches one per worker and reuses it. A context is an isolated profile inside it, like an incognito window: its own cookies, storage, cache and permissions, and it takes milliseconds to create. A page is a tab in a context. Playwright gives each test a new context, which is why tests can't leak a login or a cart into each other and why they can run in parallel safely. It also makes multi-user tests easy: two contexts in one test are two users who can't see each other's sessions, like an admin and a customer, or two people in a chat."
"How is Playwright different from Selenium under the hood?"
Show answer
"Classic Selenium sends each command to a driver over HTTP, the WebDriver protocol, and the driver talks to the browser, so every action is a request and response, and the test has to poll to find out what the page did. Playwright keeps one two-way connection to the browser, the DevTools Protocol for Chromium and an equivalent for its patched Firefox and WebKit builds, so the browser can push events: a request was made, a dialog opened, the page navigated. That's what lets it wait for the right moment instead of sleeping, intercept the network, and record traces. The trade-off: Playwright tests its own browser builds, not the Chrome or Safari your users have, although it can drive installed Chrome and Edge through channels. The newer WebDriver BiDi standard brings two-way messaging to WebDriver too, but Playwright was designed around it from the start."
"What exactly does auto-waiting cover, and what doesn't it?"
Show answer
"Two things wait automatically. Actions: before a click, Playwright waits until the element is attached, visible, stable, enabled, actually receives the click, and since 1.65 isn't inert. And web-first assertions: await expect(locator).toHaveText(...) retries until it passes or 5 seconds run out. What doesn't wait: expect(value) on a value you already read, methods that return a snapshot of now like isVisible(), textContent() or count(), page.evaluate, and anything outside the page, like a database row or an email. So the rule I use is: read the page only through expect(locator); if I need a non-page value, I wrap it in expect.poll."
"What are the default timeouts, and which ones do you change?"
Show answer
"Each test gets 30 seconds in total. Each web-first assertion retries for 5 seconds. Actions and navigations have no timeout of their own by default (actionTimeout and navigationTimeout are 0), so a stuck click shows up as the test timing out. webServer waits 60 seconds for the app to start, and there's no global timeout unless you set globalTimeout. I usually set an actionTimeout of around 10 seconds so a stuck action names itself instead of hiding behind 'Test timeout exceeded', and a globalTimeout on CI so a hung run fails rather than burning an hour. I don't raise the expect timeout to fix flakiness: every genuine failure then takes longer to report, and the flake is still there."
The test timeout is 3 seconds; an assertion's timeout is 5 seconds by default. This assertion can never pass. How long does the test take, and which timeout does the error name?
Running 1 test using 1 worker
✘ 1 [chromium] › tests/timeouts.spec.ts:5:1 › which timeout wins? (3.0s)
1) [chromium] › tests/timeouts.spec.ts:5:1 › which timeout wins? ─────────────────────────────────
Test timeout of 3000ms exceeded.
Error: expect(locator).toHaveText(expected) failed
Locator: getByRole('heading', { level: 1 })
Expected: "Welcome back"
Received: "Sign in"
Call log:
- Expect "toHaveText" getByRole('heading', { level: 1 }) with timeout 5000ms
- waiting for getByRole('heading', { level: 1 })
10 × locator resolved to <h1>Sign in</h1>
- unexpected value "Sign in"
- Test timeout of 3000ms exceeded.
5 | test("which timeout wins?", async ({ page }) => {
6 | await page.goto("/practice/");
> 7 | await expect(page.getByRole("heading", { level: 1 })).toHaveText("Welcome back");
| ^
8 | });
9 |
at <project>/tests/timeouts.spec.ts:7:57
Error Context: test-results/timeouts-which-timeout-wins--chromium/error-context.md
1 failed
[chromium] › tests/timeouts.spec.ts:5:1 › which timeout wins? ──────────────────────────────────
What’s happening
test.setTimeout(3_000) gives this test 3 seconds in total, for everything: fixtures, navigation and every assertion.
The assertion starts retrying with its own 5-second budget ("with timeout 5000ms" in the call log), but the test's 3 seconds run out first, so the run takes about 3 seconds.
The error says both things: "Test timeout of 3000ms exceeded" first, then the assertion that was running when it hit, with what it saw ("Sign in"), and the call log ending in the test timeout.
The lesson for timeouts: they nest. The test timeout is the outer limit; assertion and action timeouts live inside it. An assertion timeout longer than the test timeout can never be used up.
"When would you use the Playwright library without the test runner?"
Show answer
"When I'm automating a browser rather than testing: a script that generates PDFs or screenshots, a scraper, a one-off data migration through an admin UI, or wiring browser automation into another tool. The playwright package gives the same browser API, but no fixtures, no parallel workers, no retries, no reporters and no web-first assertions in the test-runner sense, and I'd manage browsers and contexts myself. For anything that's a test, @playwright/test is the right tool; it's where isolation, auto-waiting assertions, traces and parallelism come from."
"Does Playwright test real Safari and real phones?"
Show answer
"No, and I'd say so plainly in a test strategy. WebKit is the engine behind Safari, and Playwright's WebKit build catches most Safari layout and behaviour differences, but it isn't the Safari your users run, so Safari-specific behaviour can still differ. Device presets emulate a phone's viewport, pixel ratio, touch, user agent and isMobile, which catches responsive and touch bugs cheaply, but it's still a desktop browser. For confidence on real iOS Safari and real Android devices, I'd run a small smoke set on a device cloud, and keep the bulk of the suite on emulation."
"Which language would you choose for Playwright, and does it matter?"
Show answer
"Playwright has official bindings for TypeScript and JavaScript, Python, Java and .NET, with the same concepts in each. The Playwright Test runner, with fixtures, projects, sharding, the HTML report and UI Mode, is the Node one; the other languages plug into their own runners, like pytest, JUnit or NUnit, so some features differ. I'd pick TypeScript for a web team, because it's the same language as the front end, the runner has the most features, and new things land there first. I'd pick Python or Java if the people who'll own the tests live in that language: a suite the team can maintain beats one in the 'best' language."
"What's the test pyramid, and where does Playwright sit in it?"
Show answer
"Many fast unit tests at the bottom, fewer integration and API tests in the middle, and a small number of slow end-to-end tests at the top, because cost and flakiness go up as you go up. Playwright mostly lives at the top, driving the real app in a browser, but it reaches into the middle too: the request fixture makes it a decent API test tool, and page.route lets UI tests run against controlled data. In practice I describe it as a budget: every E2E test has to justify why a cheaper test can't catch the same bug."
"What's strict mode in Playwright, and why is it good?"
Show answer
"A locator used for an action has to match exactly one element, or the action fails with a 'strict mode violation' listing every match. Older tools silently used the first match, which is how tests ended up clicking the wrong 'Delete' button and still passing. Strictness turns an ambiguous locator into an immediate, readable failure. The fix is to scope the locator, like 'the Add to cart button inside the Wireless Mouse card', not to slap .first() on it; first() and nth() are for when position genuinely is the point."
After sign-in, the shop shows eight products, each with an "Add to cart" button (one disabled). What happens when the test clicks getByRole("button", { name: "Add to cart" })?
tests/strict.spec.ts
import{ test, expect }from"@playwright/test";test("add something to 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();awaitexpect(page.getByRole("listitem")).toHaveCount(8);await page.getByRole("button",{ name:"Add to cart"}).click();});
Show answer
npx playwright test
Running 1 test using 1 worker
✘ 1 [chromium] › tests/strict.spec.ts:3:1 › add something to the cart (1.5s)
1) [chromium] › tests/strict.spec.ts:3:1 › add something to the cart ─────────────────────────────
Error: locator.click: Error: strict mode violation: getByRole('button', { name: 'Add to cart' }) resolved to 8 elements:
1) <button type="button" data-add="kb-01">Add to cart</button> aka getByTestId('product-kb-01').getByRole('button', { name: 'Add to cart' })
2) <button type="button" data-add="kb-02">Add to cart</button> aka getByTestId('product-kb-02').getByRole('button', { name: 'Add to cart' })
3) <button type="button" data-add="ms-01">Add to cart</button> aka getByTestId('product-ms-01').getByRole('button', { name: 'Add to cart' })
4) <button disabled type="button">Add to cart</button> aka getByTestId('product-ms-02').getByRole('button', { name: 'Add to cart' })
5) <button type="button" data-add="au-01">Add to cart</button> aka getByTestId('product-au-01').getByRole('button', { name: 'Add to cart' })
6) <button type="button" data-add="au-02">Add to cart</button> aka getByTestId('product-au-02').getByRole('button', { name: 'Add to cart' })
7) <button type="button" data-add="dk-01">Add to cart</button> aka locator('li:nth-child(7) > button')
8) <button type="button" data-add="dk-02">Add to cart</button> aka locator('li:nth-child(8) > button')
Call log:
- waiting for getByRole('button', { name: 'Add to cart' })
8 | await expect(page.getByRole("listitem")).toHaveCount(8);
9 |
> 10 | await page.getByRole("button", { name: "Add to cart" }).click();
| ^
11 | });
12 |
at <project>/tests/strict.spec.ts:10:59
Error Context: test-results/strict-add-something-to-the-cart-chromium/error-context.md
1 failed
[chromium] › tests/strict.spec.ts:3:1 › add something to the cart ──────────────────────────────
What’s happening
The click doesn't wait and doesn't guess: it fails at once with "strict mode violation … resolved to 8 elements". It doesn't matter that one of them is disabled; strictness is about how many elements the locator matches, not their state.
The error lists every match, and for each one suggests a locator that would be unique, such as getByTestId('product-kb-01').getByRole('button', { name: 'Add to cart' }). For the last two it fell back to CSS (li:nth-child(7) > button), although those cards have test ids too: the suggestions are quick hints for a human, not locators to copy blindly.
The right fix states which product you mean: page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).
.first() would make it pass and click the Mechanical Keyboard, today. Tomorrow, after a re-sort, it would click something else and the test would still pass. That's the bug strict mode exists to stop.
"User-facing first, in the order the docs recommend: getByRole with the accessible name, then getByLabel for form fields, getByPlaceholder, getByText for non-interactive text, getByAltText and getByTitle. Test ids next, for things with no stable user-facing handle, agreed with developers as a contract. CSS and XPath last, and only scoped and short. Then I scope: find the container (the row, the card, the dialog) and look inside it. The reason isn't style: role-based locators break when the user experience changes and survive when only the markup changes, which is exactly the failure behaviour I want. And they double as a cheap accessibility check."
"How do you locate something with no good accessible name, like a chart or an icon?"
Show answer
"First I ask whether that's a bug: an icon button with no name is unusable with a screen reader, so the right fix is an aria-label, and then getByRole('button', { name: 'Close' }) works. If it genuinely has no user-facing handle, like a chart canvas or a price cell, I use a test id, getByTestId('cart-total'), and agree the ids with the developers so they don't vanish in a refactor; testIdAttribute in the config can point at whatever attribute the team already uses. For a chart I'd usually assert on the data behind it, a table or an aria snapshot, or use a screenshot with the volatile parts masked, rather than poke at SVG paths."
"What's the difference between isVisible() and expect(locator).toBeVisible()?"
Show answer
"isVisible() answers right now, once, with no waiting, so if the element appears 100 milliseconds later it returns false. toBeVisible() retries until the element is visible or the assertion times out. So isVisible() is for branching on the current state, which in a test is rare and usually a smell, and toBeVisible() is for asserting. The classic bug is if (await banner.isVisible()) await banner.click() that sometimes skips the click because the banner hadn't rendered yet."
The shop applies a search 300 ms after you stop typing. What do the two console.log lines print?
tests/is-visible.spec.ts
import{ test, expect }from"@playwright/test";test("isVisible vs toBeVisible",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();awaitexpect(page.getByRole("listitem")).toHaveCount(8);await page.getByLabel("Search products").fill("teapot");const message = page.getByText("No products match “teapot”.");console.log("isVisible() right away:",await message.isVisible());awaitexpect(message).toBeVisible();console.log("isVisible() after the assertion:",await message.isVisible());});
Show answer
npx playwright test
Running 1 test using 1 worker
isVisible() right away: false
isVisible() after the assertion: true
✓ 1 [chromium] › tests/is-visible.spec.ts:3:1 › isVisible vs toBeVisible (2.3s)
1 passed (2.8s)
What’s happening
fill("teapot") returns as soon as the text is in the box. The shop hasn't searched yet: it waits 300 ms for more typing.
isVisible() checks once, immediately, and the message doesn't exist yet: false. A test that branched on it, or asserted expect(await message.isVisible()).toBe(true), would fail here, every time on a fast machine and sometimes on a slow one.
toBeVisible() retries, and passes about 300 ms later when the shop renders "No products match “teapot”."
After the assertion, the same isVisible() call returns true. Nothing about the locator changed, only the timing: that's the whole difference between a snapshot read and a web-first assertion.
"A click starts a navigation. How do you wait for the next page?"
Show answer
"Usually I don't add anything: the next action or assertion waits. await expect(page).toHaveURL('/order/123') or await expect(page.getByRole('heading', { name: 'Thank you' })).toBeVisible() retries until the new page is there. The one trap is calling page.goto or reading the URL straight after a click that navigates: the click returns before the navigation finishes, so I'd put await page.waitForURL(...) between them. I don't use waitForNavigation, which is deprecated, or waitForLoadState('networkidle'), which the docs discourage because modern apps never go quiet and it waits for the wrong thing."
"How do you wait for an API call to finish before asserting?"
Show answer
"If the result shows on the page, I assert on the page and let the assertion wait. If I need the response itself, say to read an id or check the request body, I start waiting before the action and await after it: const response = page.waitForResponse(r => r.url().includes('/api/orders') && r.request().method() === 'POST'); await placeOrder.click(); expect((await response).status()).toBe(201). Starting the wait first matters: if I awaited the click and then started waiting, a fast response could already have come and gone."
"With assertions that take the whole list, so they retry as one: await expect(rows).toHaveCount(3), and await expect(rows.getByRole('heading')).toHaveText(['Wireless Mouse', 'Vertical Mouse']) for exact contents in order, or toContainText with an array for a subset. I avoid locator.all() or count() followed by a loop of assertions, because all() and count() read the list once without waiting, so the loop can check a half-rendered list. For a big structure, toMatchAriaSnapshot checks a whole block's roles and text in one go."
"How do you handle iframes, shadow DOM and new tabs?"
Show answer
"Iframes: page.frameLocator('iframe[title="Support chat"]') or locator.contentFrame(), then normal locators inside; Playwright handles cross-origin frames too. Shadow DOM: nothing special for open shadow roots, because Playwright's locators pierce them by default; closed shadow roots aren't supported. New tabs: start waiting for the popup before the click, const popup = page.waitForEvent('popup'), click the link, then await popup gives you a page to work with like any other. For a whole new window opened by window.open in the same context, context.waitForEvent('page') works too."
"How would you structure a Playwright framework for a large app with several teams?"
Show answer
"One repository, or one package in the monorepo, with a shared core and folders per domain. The core holds the config, the base fixtures (authenticated contexts per role, API clients, test data builders) and page objects for shared UI like the header and navigation. Each team owns its folder of specs and page objects, with CODEOWNERS so changes get the right reviewers. Projects cover browsers, roles and environments; tags cover suites like @smoke and team or feature areas. Conventions are written down and enforced where possible: role-based locators, no sleeps, no test.only, tests named for behaviour, with ESLint rules (there's a community eslint-plugin-playwright) and forbidOnly on CI. And a plan per domain, so it's clear what's tested end to end and what's left to cheaper tests."
"Three reasons. Fixtures are on demand: a test that doesn't ask for adminPage never pays for creating it, while beforeEach runs for every test in scope. They compose: a checkout fixture can depend on cartWith which depends on page, and each is written once. And they pair setup with teardown in one function around use(), which runs even when the test fails. beforeEach is still fine for a few lines that every test in a file really needs, like opening the page under test; I reach for fixtures when setup is shared across files or needs cleanup."
"For something expensive that tests can share without stepping on each other, created once per worker process: a test account per worker, a seeded database schema per worker, a connection to a service. The classic case is accounts: if tests change account settings, a worker-scoped fixture creates test-user-${workerInfo.parallelIndex} so parallel workers never share an account, while tests within one worker run one at a time and can safely reuse it. The thing to remember is that a worker is replaced after a failure, so the fixture runs again for the new worker: it has to cope with being set up more than once."
import{ test as base }from"@playwright/test";exportconst test = base.extend<{ cart:string[]},{ account:string}>({// Worker-scoped: set up once per worker process and shared by the tests that worker runs.
account:[async({}, use, workerInfo)=>{const name =`test-user-${workerInfo.workerIndex}`;console.log(`create ${name}`);awaituse(name);console.log(`delete ${name}`);},{ scope:"worker"},],// Test-scoped: a fresh one for every test.cart:async({}, use)=>{awaituse([]);},});export{ expect }from"@playwright/test";
tests/fixtures-demo.spec.ts
import{ test, expect }from"./fixtures";for(const n of[1,2,3,4]){test(`test ${n}`,async({ account, cart })=>{
cart.push(`item ${n}`);console.log(`test ${n}: ${account}, cart ${JSON.stringify(cart)}`);expect(n,"test 2 fails on purpose").not.toBe(2);});}
Show answer
npx playwright test
Running 4 tests using 1 worker
create test-user-0
test 1: test-user-0, cart ["item 1"]
✓ 1 tests/fixtures-demo.spec.ts:4:3 › test 1 (3ms)
test 2: test-user-0, cart ["item 2"]
delete test-user-0
✘ 2 tests/fixtures-demo.spec.ts:4:3 › test 2 (1ms)
create test-user-1
test 3: test-user-1, cart ["item 3"]
✓ 3 tests/fixtures-demo.spec.ts:4:3 › test 3 (4ms)
test 4: test-user-1, cart ["item 4"]
✓ 4 tests/fixtures-demo.spec.ts:4:3 › test 4 (0ms)
delete test-user-1
1) tests/fixtures-demo.spec.ts:4:3 › test 2 ──────────────────────────────────────────────────────
Error: test 2 fails on purpose
expect(received).not.toBe(expected) // Object.is equality
Expected: not 2
5 | cart.push(`item ${n}`);
6 | console.log(`test ${n}: ${account}, cart ${JSON.stringify(cart)}`);
> 7 | expect(n, "test 2 fails on purpose").not.toBe(2);
| ^
8 | });
9 | }
10 |
at <project>/tests/fixtures-demo.spec.ts:7:46
Error Context: test-results/fixtures-demo-test-2/error-context.md
1 failed
tests/fixtures-demo.spec.ts:4:3 › test 2 ───────────────────────────────────────────────────────
3 passed (671ms)
What’s happening
The first worker (workerIndex 0) creates test-user-0 once, and tests 1 and 2 both get it. The worker fixture is shared.
Each test's cart starts empty: test 1 sees ["item 1"], test 2 sees ["item 2"], never both. A test-scoped fixture is rebuilt for every test, so nothing leaks between them.
Test 2 fails, and Playwright throws the worker away: it tears down the worker fixture (delete test-user-0) and starts a new worker, index 1, for the remaining tests.
The new worker creates test-user-1, runs tests 3 and 4, and deletes it at the end. So "once per worker" can mean several times per run: once per worker started, including the replacements after failures.
That's why worker fixtures must be safe to create again, and why beforeAll (which also runs per worker) surprises people who expect "once per run". For true once-per-run work, use a setup project.
"Mostly no. A page object should say where things are and how to do things on that page: locators and actions like signIn(user) or applyPromo(code). The test should say what the outcome must be, so a reader sees the expectation in the test, and two tests can expect different outcomes from the same action, like a valid and an invalid code. I allow waits that make an action complete, like goto() waiting for the list to load, and occasionally a helper like expectTotal(amount) if a check is long and repeated. What I avoid is page objects that silently assert as a side effect, and page objects that grow into one class per app with hundreds of methods: split by page and by component."
"Every test creates what it needs, with unique values, through the API or a seeding service, not the UI, and doesn't depend on data another test made. I wrap that in fixtures or builders (await createOrder({ items: 2 })) so tests describe the data they need, not how it's made, and the fixture's teardown deletes it, although tests must not rely on cleanup happening, since a crashed test never cleans up. Reference data that never changes, like product catalogues, can be seeded once per environment and treated as read-only. Shared mutable accounts are the thing I remove first; they're behind most 'passes alone, fails in parallel' bugs."
"How do you handle authentication for several roles?"
Show answer
"A setup project signs in once per role through the real form and saves each session with storageState to a git-ignored file, like playwright/.auth/admin.json and user.json. Test projects depend on setup; tests pick a role with test.use({ storageState: ... }) or a fixture per role, and a test that needs two roles at once opens two contexts. Only the login tests use the form. If roles get changed by tests, I'd generate accounts per worker instead of sharing one. And for apps with MFA or SSO, the setup uses a test-environment shortcut the team controls, like a known TOTP secret, never a production identity provider."
"How do you run the same suite against different environments?"
Show answer
"baseURL from an environment variable, with a sensible default: baseURL: process.env.BASE_URL ?? 'http://localhost:3000'. Locally webServer starts the app; in CI the variable points at the preview deployment for the pull request, or at staging. Secrets like test passwords come from CI secrets as environment variables, never from the repo. If environments need different settings, like a slower staging needing a longer timeout, those become projects or config branches on the variable. Tests themselves never contain a hostname, so the same file runs everywhere. Against production I only run a small read-only smoke set with dedicated test accounts."
"How do you keep tests readable for people who didn't write them?"
Show answer
"Name each test for the behaviour, so the list of test names reads like the spec: 'express delivery adds $9.99 to the total'. Keep the arrange, act and assert visible in the test, with plumbing pushed into fixtures and page objects. Use test.step for longer flows, so the report and trace show named steps instead of fifty actions. Use the user's language in locators: getByRole('button', { name: 'Place order' }) reads like an instruction to a person. And keep one behaviour per test: if the title needs two 'and's, it's probably two tests."
"How would you move a team from a legacy Selenium suite to Playwright?"
Show answer
"Not with a big-bang rewrite. I'd start with a plan of the critical journeys and write those in Playwright first, alongside the old suite, with the new structure: setup project for auth, fixtures, page objects, role-based locators. Run both in CI for a while and compare what each catches and how often each flakes; the numbers make the case. Then retire old tests journey by journey, deleting the ones that were really unit or API tests in disguise rather than porting them. The biggest wins usually come from what the migration forces: removing sleeps, isolating test data, and cutting the suite down to what matters."
"A test fails about 1 in 20 runs on CI. Walk me through what you do."
Show answer
"First, I don't touch it until I've looked at a failing run: the error, the error context and the trace from the retry, which our config records. The trace usually shows the cause: an action on the wrong element, a response that came back slower or different, a console error. Then I reproduce it locally under pressure, --repeat-each=50 with more workers, or with CPU throttling, so I can see it fail. Then I name the cause, one of a short list: a race with the app, shared or leftover data, order dependence, time, animations, or the environment. Fix the cause, like waiting on the right condition or isolating the data, and prove it with a few hundred repeats. While I'm on it, the test is quarantined with a ticket so it doesn't block everyone. What I don't do is raise a timeout or add a sleep without understanding why."
"In roughly the order I find them: racing the app, like asserting on a value read once or clicking before a re-render; shared data, two tests using one account or one record; order dependence, a test that only passes after another; time, a date, a countdown or a time zone; animations and layout shifts, a click landing as something slides in; the environment, a slow CI machine, a shared staging server, a third-party script; and the network, a real external service being slow. Playwright removes a lot of the first category for you through auto-waiting and web-first assertions, which is why the others dominate in a healthy Playwright suite."
"Both, which is why I'm careful how they're used. On CI, one or two retries stop a rare flake from blocking a merge, and the first retry records a trace, which is the best debugging material you'll get. But a retry that passes doesn't make the test reliable: Playwright reports it as flaky, and those need to be tracked and fixed, or the suite slowly fills with tests nobody trusts. So: retries on CI, zero locally so I see every failure, flaky tests reviewed weekly, and on main failOnFlakyTests (1.52+ in the config, the CLI flag since 1.45) so new flakes fail the build instead of hiding."
With retries: 1, this test fails on its first attempt (on purpose, using testInfo.retry) and passes on the retry. Is the run green? What does the summary say?
import{ test, expect }from"@playwright/test";test("passes only on the retry",async({}, testInfo)=>{console.log(`attempt ${testInfo.retry +1}`);expect(testInfo.retry,"fails the first time on purpose").toBe(1);});
Show answer
npx playwright test
Running 1 test using 1 worker
attempt 1
✘ 1 tests/flaky.spec.ts:3:1 › passes only on the retry (6ms)
attempt 2
✓ 2 tests/flaky.spec.ts:3:1 › passes only on the retry (retry #1) (6ms)
1) tests/flaky.spec.ts:3:1 › passes only on the retry ────────────────────────────────────────────
Error: fails the first time on purpose
expect(received).toBe(expected) // Object.is equality
Expected: 1
Received: 0
3 | test("passes only on the retry", async ({}, testInfo) => {
4 | console.log(`attempt ${testInfo.retry + 1}`);
> 5 | expect(testInfo.retry, "fails the first time on purpose").toBe(1);
| ^
6 | });
7 |
at <project>/tests/flaky.spec.ts:5:61
Error Context: test-results/flaky-passes-only-on-the-retry/error-context.md
1 flaky
tests/flaky.spec.ts:3:1 › passes only on the retry ─────────────────────────────────────────────
What’s happening
Attempt 1: testInfo.retry is 0, the assertion fails with its custom message, and the run prints the failure in full, so you still see why it failed.
Playwright starts a fresh worker and retries: attempt 2 has testInfo.retry 1, and passes, marked "(retry #1)".
The summary says "1 flaky", not "1 passed". The exit code is 0, so CI stays green unless you turn on failOnFlakyTests.
In an interview, that's the point to make: retries keep the pipeline moving, but flaky is a result in its own right, reported separately, and a team that never looks at it is hiding bugs, not fixing them.
"A test passes locally and fails in CI. What's different?"
Show answer
"Usually one of five things. Speed: the CI machine is slower or busier, so a race that always won locally now loses; the trace shows it. Data: CI runs against a shared environment where other runs or people change things. Parallelism: CI runs more workers or sharded, exposing order dependence. The machine: Linux instead of macOS, different fonts for screenshots, a different time zone or locale, no GPU. Configuration: CI=true turns on retries, forbidOnly, different reporters or a different baseURL. I'd reproduce with the same Docker image, the same worker count and --repeat-each before changing anything."
"Locally, UI Mode (npx playwright test --ui) is my default: it runs tests with watch mode, and lets me step through every action with the DOM snapshot before and after, the network and the console, and pick locators. --debug opens the Inspector and pauses before the first action; await page.pause() stops at a specific point. The VS Code extension does the same with breakpoints. For CI failures, the trace from the retry, opened from the HTML report or with npx playwright show-trace. And since 1.59 there's a command-line path for agents too: npx playwright trace to read a trace, --debug=cli to step through a test from a terminal."
"What's the difference between expect.poll and toPass?"
Show answer
"expect.poll(() => value).toBe(x) repeatedly calls a function that returns a value, like an API response or a database count, until the matcher passes: a web-first assertion for things that aren't on the page. expect(async () => { ... }).toPass() retries a whole block of code, including actions and several assertions, until it all passes without throwing: useful for 'reload until the status says Done'. Both need care: keep what's inside idempotent, and give toPass a timeout, because its default is 0, which means it retries until the test times out."
"After a UI change, twenty tests fail with strict mode violations. What happened, and what do you do?"
Show answer
"The change added a second element that matches a locator that used to be unique, like a second 'Save' button in a new dialog or a duplicated header. The locators were relying on the page having only one, which is fragile. I'd fix the locators by scoping them to their real container, like the form or the dialog by its role and name, which is usually a change in a few page objects, not twenty tests. If the duplicates are visually identical controls with the same name, that's worth raising as an accessibility issue too: a screen-reader user has the same problem telling them apart."
"How do you stop flaky tests blocking the team without hiding them?"
Show answer
"Quarantine with ownership. A flaky test gets a ticket and an owner, and a @quarantine tag that the blocking pull-request job excludes with --grep-invert, while a nightly job still runs it so we see whether it's getting better or worse. Quarantine has a time limit: fixed or deleted within a sprint. We track the flaky rate from the reports, and failOnFlakyTests on main stops new flakes from creeping in. The rule I'd set as a lead: nobody 'fixes' a flake with a sleep, a bigger timeout or force: true without a reviewer agreeing on the cause."
"On every pull request: install with npm ci, install browsers with npx playwright install --with-deps (or use the official Docker image pinned to our Playwright version), build the app or point BASE_URL at the pull request's preview deployment, then run the suite sharded across a few machines. The config detects CI: retries on, traces on the first retry, forbidOnly, the blob reporter for merging and the GitHub reporter for annotations on the diff. A final job merges the blobs into one HTML report and uploads it as an artifact. Smoke tests run first as a quick signal; the full cross-browser run is on main and nightly. After a deploy, the smoke set runs against production with read-only test accounts."
"What's the difference between workers and shards?"
Show answer
"Workers are parallel processes on one machine, each with its own browser; shards split the test list across machines. You use workers to use all of one machine and shards when one machine isn't enough, and they combine: four shards with two workers each run eight tests at a time. Both depend on tests being independent. Two details: with fullyParallel the split is by test, otherwise by file, so one huge file can make one shard slow; and each shard has a fixed cost (checkout, install, browser download), so shards should each run for a few minutes, not seconds. Each shard writes a blob report, merged afterwards with npx playwright merge-reports."
"Because it pins everything that makes runs differ: the OS, the system libraries the browsers need, the fonts, and the browser builds for a given Playwright version. That gives the same result on every CI machine and on a developer's laptop when they need to reproduce a CI failure, and it's essential for screenshot tests, whose baselines depend on font rendering. The image tag must match the @playwright/test version in package.json, otherwise the browsers don't match the library. The alternative, npx playwright install --with-deps on a stock runner, works fine too; the docs advise against caching the browsers, since restoring the cache takes about as long as downloading them."
"Locally list (a line per test) and html, which I open for failures. On CI, blob on each shard so the results can be merged, github for annotations on the pull request, and the merged html report as an artifact with traces and screenshots. junit if a dashboard or test-management tool needs it. 1.65 added a failures reporter that prints only failures and passing retries as they happen, which keeps big CI logs readable, and an onlyFailures option on the HTML, JSON and JUnit reporters to keep reports small. Multiple reporters run at once, so it's not a choice of one."
Someone pushes this file with a test.only left in. What happens on their laptop, and what happens on CI, where the config sets forbidOnly: !!process.env.CI (the same as passing --forbid-only)?
Running 1 test using 1 worker
✓ 1 [chromium] › tests/search.spec.ts:15:6 › search finds the mice (1.9s)
1 passed (2.7s)
With --forbid-only, as on CI:
npx playwright test --forbid-only
Error: item focused with '.only' is not allowed due to the '--forbid-only' CLI flag: "search.spec.ts search finds the mice"
at search.spec.ts:15
13 | });
14 |
> 15 | test.only("search finds the mice", async ({ page }) => {
| ^
16 | await page.getByLabel("Search products").fill("mouse");
17 | await expect(page.getByRole("listitem")).toHaveCount(2);
18 | });
What’s happening
Locally, test.only focuses the run on that one test: "Running 1 test", and it passes. The keyboard test is silently not run. That's what only is for while you work on a test.
If that reached main without forbidOnly, CI would do the same: a green build that ran one test out of the whole suite. Nothing would look wrong.
With --forbid-only (or forbidOnly: true in the config), Playwright refuses to run at all and names the file, the line and the test: "item focused with '.only' is not allowed". The build is red until someone removes it.
That's why every generated config has forbidOnly: !!process.env.CI: one line that turns a silent coverage hole into a loud failure.
"How do you keep CI cost and time under control as the suite grows?"
Show answer
"Fix the shape first: push validation and edge cases down to unit and API tests, keep E2E for journeys, and do setup through saved sessions and the API instead of the UI. Then run smarter: a smoke job on every push, Chromium only on pull requests, all engines on main and nightly, --only-changed as a fast first pass. Then scale: fullyParallel, shards sized so each runs a few minutes, and the official image to skip installs. And measure: the HTML and JSON reports give per-test durations, so the slowest ten tests get looked at regularly. The target I'd set is a pull-request signal people trust within about ten minutes."
"Where do E2E tests belong in a deployment pipeline?"
Show answer
"In three places. On pull requests, against a preview or ephemeral environment built from the branch, so a break is caught before merge and blamed on the right change. On main, the full cross-browser run, against staging, gating the deploy. After a deploy to production, a small smoke set against production itself, with dedicated test accounts and nothing that creates real orders or emails, to catch configuration and infrastructure problems the other environments can't. The same suite does all three, chosen with tags and BASE_URL."
"How do you handle secrets and test accounts in CI?"
Show answer
"Test credentials live in the CI system's secrets and reach the tests as environment variables; nothing sensitive is committed. The saved sessions from the setup project are written at run time into a git-ignored folder (playwright/.auth) and never uploaded as artifacts, because a storage state file is a working login. Accounts are test-only, with minimal permissions, ideally created per run or per worker. Traces and HTML reports can contain whatever was on screen and in the network, so I treat report artifacts as sensitive too, with short retention."
"How would you test a resource that can't be shared, like one admin settings page?"
Show answer
"First, try to avoid sharing: give each worker its own tenant or account, so tests stay parallel. If it really is one resource, like a single global feature flag or a third-party sandbox with one slot, Playwright 1.63+ has test locks: tests that take the same lock never run at the same time, even across files and projects, while everything else stays parallel. Before 1.63 the options were serial mode for the whole file or a separate project with one worker, both of which slow everything down."
"I'd start by asking what a broken checkout costs, because that decides the depth: it's usually the highest-risk journey in the product. End to end: the happy path with a real order and confirmation; the money rules (delivery fees, discounts, tax) checked on the summary and on the confirmation, because a correct summary with a wrong charge is the bug that matters; one test that validation blocks the order; the double-submit case (the button must disable); and what happens when payment fails or times out. The payment provider: never their production page; use their test mode and test cards in a small number of tests, often nightly, and mock the payment API for the rest with page.route, so declines and timeouts are reproducible. Every validation rule and the pricing maths are unit tests; the order API's rules are API tests. Data: each test builds its own cart through the API or storage, so tests are fast and independent."
"In the browser: setInputFiles on the file input with files generated in the test (a Buffer with a name and MIME type) so there are no fixtures to maintain: a valid file, a wrong type, one over the size limit, an empty file, and a name with spaces or unicode. Check what the user sees: the error message, the preview, the file listed after upload. For drag-and-drop zones, locator.drop({ files }) (1.60+) simulates dropping files from outside the page, with the same in-memory file objects. Then the server side, as API tests with the request fixture: size limits, content sniffing rather than trusting the extension, virus scanning (mocked), and permissions on who can download it. Large-file behaviour, like progress and resumable uploads, I'd test with a mocked slow response rather than really uploading gigabytes."
The Practice Shop's account page has a "Profile picture" input that accepts images only. Write a test that tries a text file and then a 3 KB PNG, both created in memory.
Show answer
tests/upload.spec.ts
import{ test, expect }from"@playwright/test";
test.beforeEach(async({ page })=>{await page.goto("/practice/");await page.getByLabel("Username").fill("ana");await page.getByLabel("Password").fill("playwright");await page.getByRole("button",{ name:"Sign in"}).click();await page.getByRole("link",{ name:"Account"}).click();});test("a profile picture must be an image",async({ page })=>{const picture = page.getByLabel("Profile picture");await picture.setInputFiles({ name:"notes.txt", mimeType:"text/plain", buffer: Buffer.from("not a picture")});awaitexpect(page.getByText("Please choose an image file (PNG, JPG or GIF).")).toBeVisible();await picture.setInputFiles({ name:"me.png", mimeType:"image/png", buffer: Buffer.alloc(3*1024)});awaitexpect(page.getByText("Uploaded me.png (3 KB).")).toBeVisible();});
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/upload.spec.ts:11:1 › a profile picture must be an image (1.2s)
1 passed (2.0s)
What’s happening
setInputFiles accepts an object with name, mimeType and buffer instead of a path, so the test makes its files in memory and the repository has no binary fixtures.
The text file's MIME type is text/plain, and the shop rejects it with "Please choose an image file (PNG, JPG or GIF)." The test checks the message the user sees.
The "PNG" is 3,072 zero bytes labelled image/png. The shop only checks the type, so it accepts it and reports "Uploaded me.png (3 KB)." (it rounds the size to whole KB).
That last point is worth saying in an interview: this page trusts the MIME type the browser reports. A real upload feature should check the content on the server too, and that's an API test (send a text file labelled as a PNG and expect a rejection), not something a browser test can prove.
"The core is two users at once: two browser contexts in one test, each signed in from its own saved session, so I can send from Alice and assert the message appears for Bob, plus read receipts, typing indicators and unread counts on the other side. Ordering and duplicates matter, so I'd send several messages quickly and check the order on both sides. For the real-time layer, page.routeWebSocket (1.48+) lets a test play the server: push a message, drop the connection, and check the app shows 'reconnecting' and recovers without losing or repeating messages, which is very hard to arrange against a real server. Time-based behaviour like 'last seen 5 minutes ago' uses the clock API. The message protocol itself, permissions and rate limits are API or integration tests, not browser tests."
"The challenge is that live data is, by definition, not the same twice, so I'd make it deterministic. Data: mock the API with page.route (or a HAR recording) so the numbers are known and the test can assert '1,204 orders' exactly, including edge cases like zero, huge numbers and errors. Live updates: if it polls, install the clock and fastForward past the interval instead of waiting; if it uses WebSockets or server-sent events, play the server with routeWebSocket or a route. Time: fix the clock and timezoneId, since 'today' and 'last 7 days' depend on both. Charts: assert the data behind them (a table, aria labels, an aria snapshot) rather than SVG paths, and use a screenshot with masks only if the look is the requirement. One test against the real backend in staging proves the wiring; the rest stay mocked and fast."
A tiny dashboard shows "Orders today", pushed over a WebSocket. There's no server: the test serves the page with page.route, plays the WebSocket server with page.routeWebSocket (1.48+), pushes two updates, then drops the connection. Does it pass?
tests/live.spec.ts
import{ test, expect,typeWebSocketRoute}from"@playwright/test";// A tiny dashboard: it shows the number of orders, which the server pushes over a WebSocket.const dashboard =`<!doctype html><title>Orders today</title><h1>Orders today</h1><p role="status" aria-label="Order count">…</p>
<script>
const socket = new WebSocket("wss://dashboard.example/live");
socket.onmessage = (e) => (document.querySelector("p").textContent = JSON.parse(e.data).orders);
socket.onclose = () => (document.querySelector("p").textContent = "Live updates stopped. Reconnecting…");
</script>`;test("the order count follows the live feed",async({ page })=>{await page.route("https://dashboard.example/",(route)=> route.fulfill({ contentType:"text/html; charset=utf-8", body: dashboard }));let server!: WebSocketRoute;await page.routeWebSocket("wss://dashboard.example/live",(ws)=>{
server = ws;// no real server: the test plays it
ws.send(JSON.stringify({ orders:41}));});await page.goto("https://dashboard.example/");const count = page.getByRole("status",{ name:"Order count"});awaitexpect(count).toHaveText("41");
server.send(JSON.stringify({ orders:42}));awaitexpect(count).toHaveText("42");await server.close();awaitexpect(count).toHaveText("Live updates stopped. Reconnecting…");});
Show answer
npx playwright test
Running 1 test using 1 worker
✓ 1 [chromium] › tests/live.spec.ts:11:1 › the order count follows the live feed (142ms)
1 passed (826ms)
What’s happening
page.route answers the request for https://dashboard.example/ with the HTML, so the domain never has to exist. The charset=utf-8 matters: the first version of this test left it out, and the "…" in the message arrived as garbage characters, failing the last assertion.
page.routeWebSocket intercepts the page's WebSocket. Because the handler never calls connectToServer(), there is no real server: the test is the server. It sends {"orders":41} as soon as the page connects.
The test keeps the WebSocketRoute in server, then pushes {"orders":42} whenever it chooses, and the page updates. A web-first assertion waits for each value.
server.close() closes the connection from the server side, and the page shows its "reconnecting" message. Testing that path against a real server would mean killing the server mid-test; here it's one line.
It passes in a fraction of a second, every time, because nothing in it depends on timing or on a backend.
"How would you test email verification or a password reset?"
Show answer
"Use a test mailbox with an API rather than a real inbox: a local catcher like Mailpit in development and CI, or a provider's test inbox in staging. The test triggers the reset in the UI, then polls the mailbox API with expect.poll until the email arrives, extracts the link, opens it with page.goto and completes the flow. Each test uses a unique address (reset-${testInfo.workerIndex}-${Date.now()}@test.example) so parallel tests never read each other's mail. I'd also test the edges: an expired link (often with a backend test hook or the clock on the server side), a reused link, and an unknown email showing the same message as a known one, so the form doesn't reveal which accounts exist."
"How would you test a feature behind a feature flag or an A/B test?"
Show answer
"Make the variant explicit in each test rather than random. Most flag systems allow an override per request or user: a cookie, a header, a query parameter, a test user assigned to a cohort, or a local override in storage. A fixture sets it, so tests say test.use({ flags: { newCheckout: true } }) and get a known variant. If both variants are live, I'd run the affected tests in two projects, one per variant, and delete the old variant's tests when the flag is removed. What I wouldn't do is let tests hit a 50/50 split, which turns every test into a coin toss."
"How would you test an infinite-scroll list or a virtualised table?"
Show answer
"For infinite scroll, scroll the way a user does, by scrolling the last item into view (scrollIntoViewIfNeeded() or mouse.wheel), and assert that the item count grows and that a known item from page two appears; then check the end state ('no more results') with mocked data, so it doesn't take a thousand items to get there. For virtualised tables, remember only the visible rows exist in the DOM, so toHaveCount(1000) will never pass: assert on the total the UI reports, scroll to a row and check it, and check the scroll container's accessible row count if the component exposes aria-rowcount. Mocked data with known contents makes both deterministic."
"How would you test a login that uses Google or another external identity provider?"
Show answer
"I wouldn't automate Google's sign-in page: it's not our code, it's built to detect automation, and tests would break whenever it changes. Instead: in test environments, use a test identity provider the team controls (or the provider's test tenant) and sign in once in a setup project, saving the session with storageState; or use a backend test-only login endpoint that issues a session for a test user. One test can still check our side of the integration: that the 'Sign in with Google' button starts the right redirect with the right parameters, by intercepting the navigation rather than completing it."
"Run a slice of the suite per locale using projects with locale and timezoneId, and keep locators stable across languages: role-based locators use translated names, so either the tests take the expected strings from the same translation files the app uses, or they use test ids for the few elements where text varies. Check what breaks with language: dates and number formats, currency, plurals, very long German words overflowing buttons (a screenshot test with a long locale is good for that), and right-to-left layout for Arabic or Hebrew. Every translation being present is better as a unit check on the translation files than as an E2E test per string."
"You join a team with no E2E tests and a release in six weeks. What do you do?"
Show answer
"Week one, a plan, not code: list the journeys with the product owner, rank by risk, and agree on the five to ten that must never break. Then the skeleton: Playwright with a setup project for auth, a fixtures file, baseURL from an environment variable, CI on pull requests with traces and a merged report. Then the smoke tests, one per critical journey, running on every pull request within the first two weeks, because a small trusted suite beats a large ignored one. After that, the money and security rules, then failures users actually hit. Throughout, push detail into unit and API tests with the developers, and keep the flaky count at zero by fixing causes. By the release, the critical journeys are covered and the team has a pattern to extend."
Ask a friend (or record yourself) to pick one question from each topic above, plus one scenario, and answer each out loud without looking: 2 minutes for a question, 4 for the scenario. Then score yourself on the checklist in the answer. Do it twice a week until every answer scores 4 out of 5.
Show answer
For each answer, give a point for each of these:
Check
What it sounds like
A direct answer first
"Workers are processes on one machine; shards are machines." Not three sentences of warm-up.
How it works underneath
The mechanism: a fresh context per test, retries until the timeout, one connection with events.
A specific
A default (5 s, 30 s), an API name (storageState, routeWebSocket), a flag (--forbid-only), an error message ("strict mode violation").
A trade-off or a limit
What it doesn't cover, when you wouldn't use it, what it costs.
Your own example
"On the Practice Shop suite I…" or a real project. Never an invented production story: interviewers ask follow-ups.
What’s happening
Answer first, then explain: interviewers decide in the first sentence whether you know it.
The mechanism is what separates "I've used it" from "I understand it", and it's what lets you answer the follow-up you didn't prepare for.
Specifics are cheap to learn and expensive to fake. This site's chapters are full of them, and every number on it came from a real run.
Trade-offs are what senior and lead interviews are listening for: knowing when not to use a tool.
Use the Practice Shop suite (Chapter 14) as your example if you have nothing better: it's real, you've run it, and you can explain every decision in it.