The questions interviewers ask about Playwright and end-to-end testing for senior and lead roles, with strong, specific answers: fundamentals, locators and waiting, framework design, flakiness and debugging, CI and scaling, and "how would you test…" scenarios. The predict-the-outcome cards are real tests, run with Playwright 1.65.1 against the Practice Shop.
Fundamentals questions look easy, and that's why they decide interviews: everyone can say "Playwright auto-waits", fewer can say what it waits for, where it doesn't, and what that means for the tests you write. A strong answer has four beats, in about a minute: the claim, how it works underneath, the trade-off, and an example from your own work. The answers below follow that shape; say them in your own words, and swap in your own examples.
The mental model for this whole chapter: an interviewer is checking whether you've debugged this tool at 6 pm on a Friday, not whether you've read its homepage. Specifics (a default timeout, an error message, a flag) are what show it.
?Which timeout wins?
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.
These questions test whether you write tests that survive a redesign and don't flake. The interviewer wants three things: a locator strategy with a reason, knowing which calls wait and which don't, and an honest answer about when you do need an explicit wait. Chapters 4 to 6 have the detail; these are the answers.
?What does this click do?
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.
?isVisible() right after typing
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.
For a lead role, this is the section that decides the level. The interviewer wants to hear that you can design a suite that thirty people can work in for three years: clear structure, shared setup that isn't shared state, test data that scales, and conventions that keep it readable. Chapters 7, 8 and 14 have the code; these are the answers.
?How often does a worker fixture run?
account is worker-scoped and cart is test-scoped. The four tests run in one worker, and test 2 fails on purpose. What's printed, in what order?
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.
Every interviewer has lived with a flaky suite, so these questions are about judgement under pressure: do you find causes, or do you add sleeps and retries? Chapter 11 covers the tools; the answers here show the process.
?What does a pass on retry look like?
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.
For senior roles, interviewers want to hear that you've run a suite in a pipeline people depend on: how long it takes, what it costs, how failures are reported, and how it scales. Chapter 12 and Chapter 14 have the workflows; these are the talking points.
?test.only on CI
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 would you test…" questions have no single right answer, and that's the point: the interviewer is watching how you think. A strong answer has the same shape every time: clarify the risk, split the cases by level (what's E2E, what's API or unit), name the Playwright techniques, and say what can go wrong. Keep it to two or three minutes, then offer to go deeper on any part.
?Test an upload without a file on disk
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.
?Play the server for a live dashboard
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.
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.