Playwright Senior 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. 1. A Playwright suite takes 50 minutes in CI. What is usually the most effective first step?

    Correct answer: Profile the slowest tests and setup, then shard and move checks lower

    The report shows where time goes: UI logins, long flows, waits. Fixing those, moving logic checks to API or unit tests, and sharding across machines usually gives the biggest gain.

  2. 2. How does --shard=2/4 split the work?

    Correct answer: It runs about a quarter of the tests, the second part

    Shards split tests between machines. With fullyParallel: true, splitting is per test, which balances better than per file.

  3. 3. Why does fullyParallel help balance shards?

    Correct answer: Tests, not whole files, are distributed between shards

    Without it, a shard gets whole files, so one huge file can make that shard much slower than the others.

  4. 4. How do you get one report from four sharded CI jobs?

    Correct answer: Use the blob reporter in each and merge-reports at the end

    Each shard uploads its blob report as an artifact, and a final job merges them into one HTML report.

  5. 5. What does --only-changed do?

    Correct answer: Runs only test files affected by Git changes

    It compares against a Git ref and runs changed test files and those importing changed files. It's a fast pre-check, not a replacement for the full suite.

  6. 6. What does maxFailures in the config help with?

    Correct answer: Stopping a run early when something is badly broken

    If a deploy is broken, 500 failures add nothing. Stopping after, say, 10 saves CI time and keeps the signal clear.

  7. 7. What does globalTimeout limit?

    Correct answer: The whole test run

    It protects CI from a hung run. Per-test limits are timeout; fixtures can have their own timeout too.

  8. 8. Why should E2E tests not try to cover every business rule?

    Correct answer: They're slow and costly; rules are cheaper to test lower

    E2E checks that key user journeys work end to end. Combinations of rules belong to unit and API tests, which are faster and pinpoint failures.

  9. 9. How do you decide which flows deserve E2E tests?

    Correct answer: By business risk and user impact of the journeys

    Sign-up, checkout and core actions break revenue or trust when they fail. Rare admin screens may only need lighter checks.

  10. 10. How would you design fixtures for a pool of test accounts in parallel runs?

    Correct answer: Worker-scoped fixture that gives each worker its own account

    Each worker gets an account by workerIndex or creates one at start, so tests in different workers never fight over the same data.

  11. 11. Why can a saved storageState make tests fail days later?

    Correct answer: Sessions or tokens in it expire

    Generate storage state in a setup project on every run instead of committing it. Then expired sessions don't matter.

  12. 12. How do you test an app that logs in through an external SSO provider?

    Correct answer: Bypass it with a test token or a test IdP, plus few real-login tests

    Third-party login pages are slow, change without notice and may block bots. A backdoor in test environments or a fake IdP keeps most tests stable.

  13. 13. How can E2E tests handle two-factor authentication with a TOTP app?

    Correct answer: Store a test TOTP secret and generate codes in the test

    With the test account's secret, a library like otpauth computes the current code, so the flow is tested end to end.

  14. 14. How do you test a flow that sends a confirmation email?

    Correct answer: Use a test mail service or API and read the email from the test

    Tools like Mailpit or a provider's test API let the test fetch the email, extract the link and continue the flow.

  15. 15. Mocking all APIs makes E2E tests fast. What is the main risk?

    Correct answer: Tests pass while the frontend and real backend disagree

    Mocked tests check the UI against your assumptions. Keep some tests against a real backend, or add contract tests to catch drift.

  16. 16. How do you keep HAR-based mocks from going stale?

    Correct answer: Re-record them regularly and fail when requests don't match

    With notFound: 'abort', unmatched requests fail. A scheduled job with update: true refreshes recordings against the real API.

  17. 17. Why might page.route not catch some requests?

    Correct answer: A service worker can handle them before the network

    Requests served by a service worker bypass page.route. Setting serviceWorkers: 'block' makes routing predictable.

  18. 18. How do you mock a WebSocket server in a Playwright test?

    Correct answer: Use page.routeWebSocket() to intercept and answer messages

    routeWebSocket can act as the server or sit between the page and the real server to change messages.

  19. 19. What are the limits of mobile emulation in Playwright?

    Correct answer: It's a desktop engine with a mobile viewport, not a real device

    Emulation catches layout and touch issues but not real Safari on iOS, real performance or device APIs. Critical mobile flows also need real devices.

  20. 20. A test passes in Chromium but fails in WebKit. What is a sensible approach?

    Correct answer: Check it in Safari; it may be a real bug, not a test issue

    Engine differences in dates, CSS and events reach real Safari users. Confirm in Safari, then fix the app or annotate a known engine limitation.

  21. 21. Why can headless and headed runs behave differently?

    Correct answer: Focus, GPU, window size and timing differ

    Usually the difference is timing or viewport, not features. Use the same settings in CI and locally, and debug with traces.

  22. 22. How do you debug a failure that happens only in CI?

    Correct answer: Open the CI trace, reproduce in the CI Docker image, compare env

    Traces show the page state at the failure. Running the same Docker image and worker count locally often reproduces timing issues.

  23. 23. Which pattern often causes flaky tests after a click that navigates?

    await page.getByRole("link", { name: "Orders" }).click();
    const title = await page.locator("h1").textContent();
    expect(title).toBe("Orders");

    Correct answer: Reading text once, before the new page has loaded

    textContent() doesn't wait for the new heading, so it may read the old page. await expect(page.locator('h1')).toHaveText('Orders') retries.

  24. 24. Why can typing into a debounced search field cause flaky results?

    Correct answer: Results may come after the check or show stale data

    Assert on the final expected results, or wait for the matching response, instead of reading the list right after typing.

  25. 25. Why might a click land on the wrong item in a list that animates in?

    Correct answer: The element moved after its position was computed

    Playwright waits for the element to be stable, but layout shifts by other elements can still move targets. Disable animations in tests or wait for the final state.

  26. 26. How do you measure flakiness across a suite over time?

    Correct answer: Track flaky and failed results per test from CI reports

    Data from JUnit or JSON reports shows which tests flake most and whether it's getting better, so effort goes where it matters.

  27. 27. What should happen to a test that flakes often?

    Correct answer: Quarantine it with an owner and fix the root cause

    Retries hide race conditions that may be real product bugs. Quarantine keeps the main run trustworthy while the fix happens.

  28. 28. What is the trade-off of sharing one page across tests with a worker-scoped fixture?

    Correct answer: Faster tests but shared state and loss of isolation

    Reusing a page skips setup but lets state leak between tests, so a failure can cascade. Use it only for read-only, very slow setups.

  29. 29. Why are browser contexts cheap compared with launching browsers?

    Correct answer: A context is a new profile inside one running browser

    Launching a browser takes about a second; a context takes milliseconds. That's why Playwright can give each test a fresh context.

  30. 30. How do you add a custom matcher like toHaveCartTotal?

    Correct answer: Use expect.extend and export the extended expect

    Custom matchers can be async and use locators, giving readable domain checks with good failure messages.

  31. 31. What does expect.configure({ timeout: 15_000 }) give you?

    Correct answer: An expect with its own settings for slow checks

    You can create const slowExpect = expect.configure({ timeout: 15_000 }) for a few slow checks instead of raising the default for all.

  32. 32. When would you write a custom reporter?

    Correct answer: To send results to an internal dashboard or chat

    A reporter implements hooks like onTestEnd and onEnd and receives results, steps and attachments.

  33. 33. What does box: true on a test.step do?

    Correct answer: Errors point to the step call, not code inside it

    In page object methods, boxing hides internal lines, so the report points to the line in the test that called the method.

  34. 34. How can a fixture fail tests that print console errors?

    Correct answer: An auto fixture listens to console/pageerror and checks at the end

    Collecting errors and asserting after use() catches crashes that don't break the visible UI.

  35. 35. Where should a test write temporary files so parallel tests don't clash?

    Correct answer: To testInfo.outputPath(), unique per test

    Output paths are per test and per retry, and are kept with other test results.

  36. 36. What is the main maintenance problem of a huge "god" page object?

    Correct answer: Many tests depend on one class, so changes ripple far

    Split page objects by page or component and compose them. Smaller units are easier to change and review.

  37. 37. What is an alternative to deep page object inheritance?

    Correct answer: Composition: small component objects and fixtures

    Components like Header or DatePicker can be reused across pages. Fixtures assemble what each test needs.

  38. 38. How should locators be chosen in an app with several languages?

    Correct answer: Roles with names from translations, or test IDs where needed

    Reading names from the same translation files or running each locale as a project keeps tests correct for every language.

  39. 39. What should a team policy on data-testid say?

    Correct answer: Use it when role and name aren't stable or unique

    Roles test accessibility for free. Test IDs fill gaps like repeated cards or canvas widgets, and should be stable, not generated.

  40. 40. When is it reasonable to seed data directly in the database?

    Correct answer: When no API exists and the schema is stable and owned

    Direct SQL is fast but couples tests to the schema and can skip business logic. Public or test APIs are usually safer.

  41. 41. How do you clean up data created by E2E tests?

    Correct answer: Teardown in fixtures, plus a periodic job for leftovers

    Fixtures delete what they created even on failure. Crashed runs still leave data, so a scheduled cleanup by prefix helps.

  42. 42. Why run E2E tests against preview deployments of each pull request?

    Correct answer: Bugs are caught before merge, on the exact code

    Pointing baseURL at the preview URL tests the real build and infrastructure before it reaches the main branch.

  43. 43. What is a good use of Playwright tests against production?

    Correct answer: A few read-only smoke checks after each deploy

    Light smoke checks on key pages catch broken deploys quickly. Writes need test accounts and care not to affect real users.

  44. 44. Why is Playwright a poor tool for load testing?

    Correct answer: Each browser is heavy, so realistic load needs huge resources

    Load tools like k6 simulate thousands of users with HTTP calls. Playwright can still measure page performance for a single user.

  45. 45. How can Playwright collect performance data for a page?

    Correct answer: Read Performance API values with page.evaluate

    Navigation and paint timings, or Chromium-only CDP metrics, can be collected and tracked, with care since CI timing is noisy.

  46. 46. What is the trade-off of using CDP sessions in Playwright tests?

    Correct answer: They work only in Chromium-based browsers

    CDP gives low-level access like network throttling or coverage, but those tests won't run in Firefox or WebKit.

  47. 47. What are the limits of Playwright component testing?

    Correct answer: It's experimental, and components need serializable props

    Components are mounted in a real browser through a bundler. Complex props like callbacks have limits, and setup differs from app tests.

  48. 48. When does visual regression testing pay off?

    Correct answer: For stable, high-value screens like design systems

    Snapshots of changing pages produce constant noise and approvals. Component libraries and key screens benefit most.

  49. 49. How do you make screenshot tests stable across machines?

    Correct answer: Generate and compare baselines in the same Docker image

    Fonts, GPU and OS rendering differ. A shared container with fixed fonts gives the same pixels everywhere.

  50. 50. What does toHaveScreenshot do to reduce flakiness before comparing?

    Correct answer: Waits until two screenshots in a row are identical

    It retries capturing until the page is stable, then compares with the baseline using the configured threshold.

  51. 51. What are Playwright test agents?

    Correct answer: AI agents that plan, generate and repair tests

    The planner explores the app and writes a test plan, the generator turns it into tests, and the healer tries to fix failing ones. Their output still needs review.

  52. 52. What is the main risk of letting an AI agent "heal" failing tests?

    Correct answer: It may change the test to pass when the app is broken

    A failure can be a real bug. Automatic fixes need human review to confirm the test still checks the intended behaviour.

  53. 53. What are the limits of code recorded with codegen?

    Correct answer: It records actions but not intent, structure or good checks

    Recorded code is a starting point. Engineers add assertions, extract page objects, remove noise and use test data properly.

  54. 54. How do you run Playwright for several apps in a monorepo?

    Correct answer: Separate configs or projects per app, each with its webServer

    Per-app configs keep base URLs, servers and dependencies clear, and CI can run only the apps that changed.

  55. 55. How do you start several services before tests?

    Correct answer: Pass an array of servers to webServer

    Each entry has its own command, URL and timeout, e.g. a frontend and a mock API.

  56. 56. How would you test a payment flow in E2E?

    Correct answer: Use the provider's sandbox and test cards, plus a few mocked edge cases

    Sandboxes support success, decline and 3-D Secure flows. Mocks cover rare errors; one real smoke payment may run in production with care.

  57. 57. Why might page.waitForURL be needed after a form submit?

    Correct answer: To make sure navigation finished before the next step

    Actions don't wait for navigation they start. Asserting toHaveURL or a visible element on the next page syncs the test.

  58. 58. How should a team handle tests that need many minutes, like big imports?

    Correct answer: Test the logic lower; keep one E2E with test.slow() or a tag

    A long E2E test slows every run. Unit and API tests cover the variations; a tagged E2E can run nightly.

  59. 59. What does a nightly full run add to PR runs of a smaller subset?

    Correct answer: Wider coverage like all browsers, without slowing every PR

    PRs run a fast, high-value set; nightly runs the full matrix. Failures in nightly need an owner who acts the next morning.

  60. 60. How do you check that every route has no serious accessibility violations?

    Correct answer: Loop over routes and run axe with a shared fixture

    A fixture configured with the team's rules makes the check consistent; failures list the rule, element and fix.

  61. 61. What does page.clock.install() let you test that real timers make impractical?

    Correct answer: Session timeouts and scheduled UI changes, in milliseconds

    With a controlled clock you can jump 30 minutes ahead and check the logout warning without waiting.

  62. 62. How do you test an Electron app with Playwright?

    Correct answer: Use the experimental _electron API to launch and drive it

    Playwright can launch Electron, access its windows as pages and evaluate code in the main process.

  63. 63. Why should fixtures not hide the main action of a test?

    Correct answer: Readers must see what's tested without opening fixtures

    Fixtures should prepare state (users, data, pages). The behaviour under test should stay visible in the test body.

  64. 64. What is a reasonable policy for test.skip and fixme in a large suite?

    Correct answer: Each needs a reason and a ticket, reviewed regularly

    Skipped tests silently reduce coverage. Reports listing annotations with reasons help keep the number low.

  65. 65. Why keep trace files small in big suites?

    Correct answer: Storage and upload time grow fast with many tests

    Recording only on retry or failure, and limiting snapshots, keeps CI artifacts manageable.

  66. 66. How do you make sure tests don't depend on run order?

    Correct answer: Run with fullyParallel and random sharding regularly

    If tests only pass in one order, they share state. Running them in parallel and in different groupings exposes that.

  67. 67. What should you check first when a test times out on click()?

    Correct answer: Which actionability check failed, shown in the error and trace

    The log says e.g. "element is not enabled" or "another element would receive the click", which points to the real cause.

  68. 68. How do you test that a feature behind a flag works in both states?

    Correct answer: Set the flag per test through an API, cookie or init script

    Controlling the flag in the test makes both paths deterministic, and projects can run the suite with the flag on and off.

  69. 69. Why may tests that pass with one worker fail with many?

    Correct answer: They share data or the backend can't handle the load

    Parallel runs reveal shared accounts, unique constraints or rate limits. Fix with isolated data or by sizing the test environment.

  70. 70. How should E2E test code be reviewed?

    Correct answer: Like product code: readability, isolation, locators and asserts

    Reviewers look for missing assertions, fragile locators, shared state and fixed waits, which prevents a flaky suite.

  71. 71. What is the purpose of test.info().annotations?

    Correct answer: Adding metadata like issue links to tests in reports

    Annotations with types like issue or perf appear in the HTML report and in custom reporters.

  72. 72. Why should a large suite avoid beforeAll that creates shared state for a file?

    Correct answer: After a failure the worker restarts, and state may be half-built

    beforeAll reruns in new workers and couples tests. Per-test fixtures or worker fixtures are more predictable.

  73. 73. How do you handle third-party scripts like chat widgets that slow tests?

    Correct answer: Block them with page.route unless the test is about them

    Blocking analytics and widgets removes noise and network flakiness. A separate test can check the integration itself.

  74. 74. What is the main benefit of running each locale or tenant as a Playwright project?

    Correct answer: The same tests check every variant without duplication

    Project use options set locale, base URL or tenant, and the report groups results by project.

  75. 75. When is checking the network layer in E2E tests better than checking the UI?

    Correct answer: When the effect is invisible, like an analytics event

    Some behaviour, such as tracking calls or retries, has no visible result. Asserting on requests covers it.

  76. 76. What makes a good E2E failure message for the team?

    Correct answer: It says what the user couldn't do and shows the evidence

    Steps, custom assertion messages and attached traces turn "timeout 30000ms" into "couldn't add item to cart: button disabled".

  77. 77. What is the role of Playwright in a test strategy alongside unit and API tests?

    Correct answer: A thin layer for key journeys and cross-browser checks

    Broad logic coverage comes from fast lower-level tests. Playwright proves the pieces work together in real browsers.