Playwright Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What does
fullyParallel: truechange?Correct answer: Tests inside one file also run in parallel
By default files run in parallel, but tests within a file run in order in one worker.
fullyParallelspreads individual tests across workers, which requires every test to be independent.2. Why do many configs set
workers: process.env.CI ? 1 : undefined?Correct answer: CI machines are often small, and one worker is more stable
Locally Playwright uses about half the CPU cores. On a small CI runner, many browsers fight for CPU and cause timeouts. Teams with bigger runners or sharding raise the number.
3. What does
retries: process.env.CI ? 2 : 0achieve?Correct answer: Retries failures in CI but shows them at once locally
Locally you want to see a failure immediately. In CI, retries absorb rare infrastructure glitches, and tests that pass on retry are reported as flaky so they can be fixed.
4. What does a test marked "flaky" in the Playwright report mean?
Correct answer: It failed first and passed on a retry
Flaky tests pass the run but need attention: they hide race conditions or shared state.
--fail-on-flaky-teststurns them into failures.5. What does
forbidOnly: !!process.env.CIprotect against?Correct answer: A committed
test.onlysilently skipping the rest in CIWith this setting, a run in CI fails if any
test.onlyis present, instead of reporting green after running one test.6. What is the difference between
actionTimeoutand the testtimeout?Correct answer: One limits each action; the other the whole test
actionTimeout(no limit by default) caps a singleclickorfill. The test timeout (30 s) covers everything in the test, including hooks.7. How do you change options like locale for one group of tests only?
test.describe("German UI", () => { test.use({ locale: "de-DE" }); test("shows prices", async ({ page }) => { /* ... */ }); });Correct answer: Call
test.use()inside adescribeblocktest.useoverridesuseoptions for a file or describe block, so the group gets its own context settings.8. How do you create a custom fixture?
const test = base.extend<{ todoPage: TodoPage }>({ todoPage: async ({ page }, use) => { const todo = new TodoPage(page); await todo.goto(); await use(todo); }, });Correct answer: Extend the base
testand provide the value viauseCode before
use()is setup, code after it is teardown. Tests that listtodoPagein their arguments get it ready to use.9. When does teardown code in a fixture run?
myFixture: async ({}, use) => { const user = await createUser(); await use(user); await deleteUser(user.id); },Correct answer: After the test finishes, even when it fails
Code after
await use()runs after the test, whatever its result. This keeps cleanup next to setup.10. What is a worker-scoped fixture?
Correct answer: Set up once per worker process and shared by its tests
Declare it with
{ scope: 'worker' }. It suits expensive things like a test account or a started service, shared by all tests in that worker.11. What does
{ auto: true }do for a fixture?Correct answer: Runs it for every test, even if no test asks for it
Automatic fixtures suit cross-cutting work like collecting logs or failing on console errors for every test.
12. What is the recommended way to log in once and reuse it?
Correct answer: A setup project saves
storageState, others depend on itThe setup project logs in and writes cookies and storage to a file. Projects with
dependencies: ['setup']load it withstorageState, so tests start logged in.13. How do you test with two different roles in one test, e.g. admin and user?
Correct answer: Create two browser contexts, each with its own
storageStateEach context is isolated, so
browser.newContext({ storageState: 'admin.json' })and a user context can act side by side, like two people in a chat.14. What are project
dependenciesused for?Correct answer: Running one project, like setup, before others
Dependent projects run only after their dependencies pass. Unlike
globalSetup, setup projects appear in the report and support traces and fixtures.15. Why prefer a setup project over
globalSetup?Correct answer: It has fixtures, traces and shows in the report
globalSetupis a plain function: no fixtures, no traces, and failures are harder to debug. A setup project is a normal test with all the tooling.16. What does this route do?
await page.route("**/api/products", (route) => route.fulfill({ json: [{ id: 1, name: "Mock" }] }) );Correct answer: Returns fake JSON instead of calling the real API
route.fulfillanswers the request from the test. It's useful for edge cases like empty lists or errors that are hard to get from a real backend.17. How do you simulate a server error for one endpoint?
Correct answer:
route.fulfill({ status: 500 })in apage.routehandlerMocking a 500 lets you check the error state of the UI deterministically, without breaking a shared backend.
18. How do you change a real API response slightly, e.g. one field?
await page.route("**/api/user", async (route) => { const response = await route.fetch(); const json = await response.json(); json.plan = "pro"; await route.fulfill({ response, json }); });Correct answer: Fetch it with
route.fetch()and fulfill a modified copyThis keeps the real backend in the loop while forcing one condition, such as a paid plan.
19. What does
route.abort()do?Correct answer: Makes the request fail, like a network error
Aborting requests can block images or analytics to speed up tests, or simulate a failed network call.
20. How do you wait for a specific API response after a click?
const responsePromise = page.waitForResponse("**/api/orders"); await page.getByRole("button", { name: "Place order" }).click(); const response = await responsePromise;Correct answer: Start
waitForResponsebefore the click, then await itStarting to wait before the action avoids missing a fast response. You can then assert on its status or body.
21. What is
routeFromHARused for?Correct answer: Serving recorded network traffic to the page
A HAR file records requests and responses. Replaying it gives stable, offline tests;
update: truere-records it.22. How do you parameterize a test over several inputs?
for (const email of ["", "bad", "a@"]) { test(`rejects "${email}"`, async ({ page }) => { // ... }); }Correct answer: Loop and declare a test with a unique title for each
Playwright collects tests by running the file, so a loop creates one test per value. Titles must be unique.
23. How do you pass a value like a user role through project options?
Correct answer: Declare an option fixture and set it in each project's
useOption fixtures (
{ option: true }) have defaults that projects override, so one test suite can run with different roles or tenants.24. What does
test.stepgive you?Correct answer: Named steps in reports and traces
Steps group actions under readable names, so a failure shows "Add item to cart" instead of a raw locator.
25. What does
expect.softdo?Correct answer: Records a failure but lets the test continue
Soft assertions collect several problems in one run, such as many fields on a form. The test is still marked failed at the end.
26. When is
expect.polluseful?await expect.poll(async () => { const res = await request.get("/api/jobs/42"); return (await res.json()).status; }).toBe("done");Correct answer: To retry a non-locator value until it matches
Web-first assertions retry locator checks.
expect.pollretries any async function, e.g. waiting for a background job.27. How do you add a custom message to an assertion?
Correct answer:
await expect(total, 'cart total').toHaveText('$10')The message appears in the report and makes failures easier to understand without opening the code.
28. How do you attach a file or text to the test report?
Correct answer:
await testInfo.attach('log', { body, contentType })Attachments such as server logs or API responses appear next to the failing test in the HTML report.
29. What happens the first time
toHaveScreenshot()runs?Correct answer: It fails and saves a baseline image
There's nothing to compare against yet, so it writes the expected image. Later runs compare against it.
--update-snapshotsrefreshes baselines on purpose.30. Why are screenshot baselines often stored per platform?
Correct answer: Fonts and rendering differ between operating systems
Snapshot file names include the browser and platform. Many teams generate baselines in the same Docker image used in CI.
31. How do you hide a changing element, like a clock, in a screenshot test?
Correct answer: Use the
maskoption with its locatorMasked areas are covered with a box.
animations: 'disabled'andmaxDiffPixelsalso help reduce noise.32. What does
locator.or()do?const dialog = page.getByText("Confirm security settings"); const newEmail = page.getByRole("button", { name: "New email" }); await expect(newEmail.or(dialog).first()).toBeVisible();Correct answer: Matches either locator, for when one of two may appear
It handles UIs that show one of two states. Use
first()because both might match at once.33. What does
locator.and()do?Correct answer: Matches elements that satisfy both locators
For example
page.getByRole('button').and(page.getByTitle('Subscribe'))finds a button that also has that title.34. How do you find list items that do NOT contain a "Sold out" label?
Correct answer:
items.filter({ hasNotText: 'Sold out' })hasNotandhasNotTextremove matches containing an element or text.35. Do Playwright locators work inside open shadow DOM?
Correct answer: Yes, they pierce open shadow roots by default
CSS and role locators look into open shadow roots automatically. XPath does not, and closed shadow roots aren't reachable.
36. Why is
force: trueon a click risky?Correct answer: It skips actionability checks and may hide real UI bugs
If an overlay covers the button, a real user can't click it. Forcing the click makes the test pass while the bug stays.
37. What does
locator.waitFor()do?Correct answer: Waits until the element reaches a state like
visibleIt's useful before reading values with methods that don't wait, though an assertion is usually clearer.
38. Why can
await locator.isVisible()cause flaky tests?Correct answer: It checks once without waiting for the element
isVisible()returns the state right now. Using it in conditions orexpect(...).toBe(true)races with rendering; web-first assertions retry.39. Why is
waitForLoadState('networkidle')discouraged?Correct answer: Many apps never go quiet, and it doesn't mean UI is ready
Polling, analytics or websockets keep the network busy. Waiting for a visible element or a specific response is more reliable.
40. How do you run code in the page before any of its scripts load?
Correct answer:
page.addInitScript()Init scripts run in every new document before page scripts, e.g. to stub
Math.randomor set a feature flag inlocalStorage.41. What does
page.evaluate()do?const width = await page.evaluate(() => window.innerWidth);Correct answer: Runs a function in the page and returns the result
The function runs in the browser, so it can't use test variables unless passed as an argument. Results must be serializable.
42. How do you test how a page behaves offline?
Correct answer:
await context.setOffline(true)Offline mode makes requests fail like real network loss. Combine it with checks of offline banners or retries.
43. How do you test a location-based feature?
Correct answer: Set
geolocationand grant thegeolocationpermissionContext options like
geolocation,locale,timezoneIdandpermissionsemulate the user's environment.44. How do you test dark mode styles?
Correct answer:
test.use({ colorScheme: 'dark' })colorSchemeemulatesprefers-color-scheme, so CSS media queries respond as for a real user.45. What does
page.clockhelp with?Correct answer: Controlling time to test timers and dates
clock.install()andclock.fastForward('30:00')test session expiry or countdowns without waiting.46. How do you drag an item onto a drop zone?
Correct answer:
await item.dragTo(dropZone)dragTodoes the mouse down, move and up. Libraries with custom logic may need manualpage.mousesteps.47. What does
trial: trueon an action do?Correct answer: Checks actionability without performing it
A trial click waits until the element could be clicked. It's handy for waiting before hovering or for debugging.
48. How do you read the texts of all matching elements?
Correct answer:
await items.allTextContents()allTextContentsandallInnerTextsreturn arrays but don't wait. PrefertoHaveText([...])for assertions, which retries.49. Which assertion checks the texts of a whole list in order?
Correct answer:
await expect(items).toHaveText(['A', 'B', 'C'])Passing an array to
toHaveTextmatches each element in order and checks the count.50. What does
npx playwright test --last-faileddo?Correct answer: Re-runs only tests that failed last time
It speeds up the fix-and-check loop after a big run.
51. How do you check whether a test is flaky locally?
Correct answer: Run it many times with
--repeat-each=20Repeating a test, especially with several workers, surfaces timing problems that appear only sometimes.
52. What does
video: 'retain-on-failure'do?Correct answer: Records videos but keeps them only for failed tests
Recording costs a bit of speed. Keeping only failures saves disk space while still showing what happened.
53. What is the blob reporter for?
Correct answer: Saving results from shards to merge into one report
Each shard writes a blob report;
npx playwright merge-reportscombines them into one HTML report.54. Which reporter is common for CI systems like Jenkins or GitLab?
Correct answer:
junitThe JUnit XML format is read by most CI tools to show test results in merge requests and dashboards.
55. Why use the official Playwright Docker image in CI?
Correct answer: It has browsers and system dependencies preinstalled
The image version must match the
@playwright/testversion. It also gives consistent screenshots between machines.56. Which artifacts should a CI job keep after a failed Playwright run?
Correct answer: The HTML report with traces, screenshots and videos
Uploading
playwright-report/andtest-results/lets anyone open the trace of a CI failure without reproducing it.57. What does a Page Object usually contain?
Correct answer: Locators and actions for one page or component
Page objects hide locators behind methods like
login(email, password). When the UI changes, only the page object changes.58. Why are page objects often provided through fixtures?
Correct answer: Tests get them ready to use without repeated setup
A fixture creates the page object, maybe navigates, and passes it in, so each test starts directly with its logic.
59. Where should assertions live in a Page Object Model?
Correct answer: Mostly in tests; page objects expose actions and locators
Keeping checks in tests shows what each test verifies. Page objects can offer helper assertions, but hiding all checks makes tests unclear.
60. What does
test.describe.configure({ retries: 3 })do?Correct answer: Sets retries for the tests in that describe block
Per-group settings help for known unstable areas while you fix them, without raising retries globally.
61. How can a test know it's running as a retry?
Correct answer: Check
testInfo.retry, which is above 0 on retriesIt can be used to clear caches or collect extra logs on retry.
62. What happens to the worker process after a test fails?
Correct answer: It's discarded, and a new worker starts for later tests
Playwright starts a fresh worker after a failure so broken state doesn't affect other tests.
beforeAllhooks run again in it.63. How do you load environment-specific values like a staging URL?
Correct answer: Read env variables, e.g. with dotenv, in the config
The config is TypeScript, so it can read
process.env.BASE_URLand choose settings per environment.64. How can you check a page for accessibility issues in a Playwright test?
Correct answer: Run axe-core via
@axe-core/playwrightAxe finds many issues like missing labels or low contrast. Manual checks are still needed for others.
65. What does
toMatchAriaSnapshotcompare?Correct answer: The accessibility tree against a YAML template
ARIA snapshots check roles, names and structure. They're less fragile than pixel snapshots and also catch accessibility regressions.
66. Which locator filters buttons by their checked state, like a toggle?
Correct answer:
getByRole('checkbox', { checked: true })Role options like
checked,pressed,expanded,selectedandlevelmatch ARIA states.67. How do you handle a cookie consent banner that appears randomly?
Correct answer: Use
page.addLocatorHandlerto close it when it appearsA locator handler runs whenever the overlay blocks an action, then the action continues. Setting a consent cookie up front is another option.
68. How do you keep test data separate when tests run in parallel workers?
Correct answer: Use unique data, e.g. names with
testInfo.workerIndexUnique users or prefixes per worker or test prevent collisions, like two tests editing the same cart.
69. What does
test.describe.configure({ mode: 'serial' })do when a test fails?Correct answer: Later tests in the group are skipped
Serial groups depend on order, so a failure stops the rest. This is why independent tests are preferred.
70. How do you make an API request with the cookies of the logged-in page?
Correct answer: Use
page.request, which shares the context's cookiespage.requestandcontext.requestshare storage with the browser context. The standalonerequestfixture has its own.71. How do you create a request context with an auth header for API tests?
const api = await playwright.request.newContext({ baseURL: "https://api.example.com", extraHTTPHeaders: { Authorization: `Bearer ${token}` }, });Correct answer:
request.newContextwithextraHTTPHeadersA dedicated context keeps settings like base URL and headers. Remember to
dispose()it when done.72. Why combine API setup with UI checks in one test?
Correct answer: Setup is fast and stable, and the UI check stays focused
Creating an order via API and only checking how the UI shows it saves time and removes flaky steps unrelated to the feature.
73. Which
useoption records traces only for failed tests?Correct answer:
trace: 'retain-on-failure'It records every test but deletes traces of passing ones.
on-first-retryis cheaper;onkeeps everything.74. What do you see in the trace viewer for each action?
Correct answer: DOM snapshots before and after, network, console and source
You can inspect the page at any step, check which element a locator hit, and see failed requests, which makes CI failures debuggable.
75. How do you test that a request is sent with the right body?
const request = page.waitForRequest("**/api/feedback"); await page.getByRole("button", { name: "Send" }).click(); expect((await request).postDataJSON()).toEqual({ rating: 5 });Correct answer: Wait for the request and check
postDataJSON()Checking what the frontend sends catches bugs that a mocked backend would otherwise hide.