Automation Interview
Top 50 Playwright Interview Questions and Answers (2026)
Prepare top playwright interview questions with 50 practical answers on locators, fixtures, APIs, CI, debugging, architecture, and senior SDET scenarios.
33 min read | 5,361 words
TL;DR
The strongest answers to top Playwright interview questions combine correct API knowledge with engineering judgment. Prepare the 50 answers below, then practice explaining one real framework, one difficult flake, one CI improvement, and one risk-based test-design decision.
Key Takeaways
- Explain Playwright concepts through reliability, isolation, maintainability, and user risk rather than definitions alone.
- Know locator strictness, web-first assertions, fixtures, browser contexts, projects, and network timing in practical depth.
- Separate observation with waitForResponse, control with routing, and direct API checks with APIRequestContext.
- Describe retries and traces as diagnostic support, never as substitutes for fixing flaky tests.
- Connect CI parallelism and sharding to data isolation, environment capacity, and useful failure artifacts.
- Prepare concise project stories that state the problem, decision, implementation, evidence, and tradeoff.
These top playwright interview questions cover the capabilities and engineering decisions most QA automation and SDET interviews test in 2026. The 50 model answers address locators, assertions, fixtures, architecture, authentication, API and network testing, parallel execution, CI, debugging, and scenario design.
Do not memorize sentences. Use each answer as a structure, then add an example from your work. Interviewers trust candidates who can explain the requirement, choice, evidence, and tradeoff more than candidates who list every method name.
This guide is suitable for intermediate and senior preparation. Junior candidates can focus first on questions 1 through 20, while experienced candidates should be ready to defend the architecture and failure-analysis answers with concrete project details.
TL;DR
| Interview area | What a strong answer demonstrates |
|---|---|
| Playwright fundamentals | Correct browser, context, page, locator, and runner mental models |
| Locator strategy | User-facing semantics, strictness, scoping, and maintainability |
| Synchronization | Event registration, actionability, web-first assertions, no fixed sleeps |
| Framework design | Typed fixtures, clear lifecycle, composition, and useful abstractions |
| Network and API | Correct choice among observation, interception, and direct requests |
| Reliability | Isolated data, causal flake analysis, traces, and bounded retries |
| Scale and CI | Projects, workers, sharding, environment capacity, and artifacts |
| Senior scenarios | Risk-based layering, tradeoffs, review standards, and ownership |
A compact answer pattern:
- Give the direct definition.
- Explain when you use it.
- Name one failure mode or tradeoff.
- Add a real example or measurable outcome.
1. What top playwright interview questions measure
Playwright interviews rarely stay at syntax. A hiring team wants evidence that you can build tests that remain trustworthy when the UI changes, the suite runs in parallel, and CI is slower than a laptop.
Expect evaluation across four levels:
- API correctness: You know Locator, BrowserContext, fixtures, routing, and runner configuration.
- Test design: You choose the right layer and assert meaningful user outcomes.
- Reliability: You isolate state, synchronize with events, and diagnose flakes from evidence.
- Delivery: You review code, protect secrets, structure CI, and communicate risk.
A weak answer says, "Playwright auto-waits." A strong answer explains that locator actions perform relevant actionability checks, locator assertions retry, fixed sleeps are discouraged, and neither feature can repair shared test data or an incorrectly ordered response listener.
Prepare a short system description before the interview. State the application, browser coverage, approximate suite shape without inventing numbers, test layers, CI trigger, data strategy, authentication approach, artifacts, and your ownership. Be precise about what you personally designed or changed.
For each project story, use this sequence: problem, evidence, decision, implementation, result, and remaining tradeoff. If you cannot disclose company details, describe the technical shape with anonymized domain names.
2. Build a Small Reference Project Before the Interview
A runnable project makes answers concrete. Use Playwright Test with TypeScript, one local server, two browser projects, traces on retry, and semantic locators.
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
reporter: [['list'], ['html', { open: 'never' }]],
use: {
baseURL: 'http://127.0.0.1:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
],
webServer: {
command: 'npm run start:e2e',
url: 'http://127.0.0.1:3000/health/ready',
reuseExistingServer: !process.env.CI,
},
});
Your reference scenario should create data through an API, authenticate safely, perform one browser mutation, validate a response and UI state, and clean up. Add one controlled error with page.route. Run it in CI and inspect a trace at least once.
This small system gives you authentic examples for fixtures, locators, network waiting, data isolation, retries, and reporting. It also reveals gaps more quickly than reading disconnected API lists.
Keep credentials and storage-state files out of version control. Use a restricted test account or per-test data, not a personal production login.
3. Master Locators, Actionability, and Assertions
Locator quality is a frequent interview discriminator. Prefer getByRole, getByLabel, getByPlaceholder, getByText, getByAltText, getByTitle, and intentional test IDs. Use CSS when DOM structure is itself the contract, and treat XPath as a last resort.
import { test, expect } from '@playwright/test';
test('updates notification settings', async ({ page }) => {
await page.goto('/settings/notifications');
await page.getByRole('checkbox', {
name: 'Weekly quality summary',
}).check();
await page.getByRole('button', { name: 'Save settings' }).click();
await expect(page.getByRole('status'))
.toHaveText('Notification settings saved');
});
The checkbox locator expresses an accessible user contract. The action performs relevant actionability checks. The status assertion retries until the text matches or its timeout expires.
Be ready to explain strictness. An action on a locator that resolves to multiple elements fails because Playwright refuses to guess. Scope the locator to a meaningful region or row rather than using first() to silence ambiguity.
Also distinguish action auto-waiting from assertion retrying. click waits for actionability, but it cannot prove a later business result. expect(locator).toHaveText retries the postcondition. For deeper practice, read Playwright locator best practices.
4. Explain Fixtures and Framework Structure Clearly
Fixtures represent dependencies with setup, use, and teardown. They are stronger than a large beforeEach when the suite needs typed values, dependency ordering, and reliable cleanup.
import { test as base, expect } from '@playwright/test';
type Workspace = {
id: string;
name: string;
};
type Fixtures = {
workspace: Workspace;
};
export const test = base.extend<Fixtures>({
workspace: async ({ request }, use) => {
const create = await request.post('/api/test/workspaces', {
data: { name: 'E2E Workspace' },
});
expect(create.ok()).toBe(true);
const workspace = await create.json() as Workspace;
await use(workspace);
const remove = await request.delete(
'/api/test/workspaces/' + workspace.id,
);
expect(remove.ok()).toBe(true);
},
});
export { expect };
Code before use creates the dependency. The test runs while the fixture awaits use. Code after use cleans up even when the test fails, subject to process-level interruption.
Test-scoped fixtures favor isolation. Worker-scoped fixtures can reduce expensive setup but are safe only for resources tests can share. A mutable account is usually a poor worker fixture.
Framework structure should expose intent rather than wrap Playwright. Prefer typed fixtures, small API clients, data builders, and composed page or component objects. Avoid a base page with generic click, fill, sleep, and selector methods. Rehearse fixture scope with the Playwright fixtures guide.
5. Prepare Network and API Testing Decisions
Interviewers often ask one scenario that can be solved three ways. Explain the boundary:
| Tool | Role |
|---|---|
| page.waitForRequest | Observe an outgoing browser request |
| page.waitForResponse | Observe a completed browser response |
| page.route | Continue, modify, fulfill, or abort browser traffic |
| browserContext.route | Apply routing across pages in a context |
| APIRequestContext | Call an API directly for setup or service tests |
Register event waits before the action:
const responsePromise = page.waitForResponse(response =>
new URL(response.url()).pathname === '/api/profile' &&
response.request().method() === 'PUT',
);
await page.getByRole('button', { name: 'Save profile' }).click();
const response = await responsePromise;
expect(response.status()).toBe(200);
await expect(page.getByRole('status')).toHaveText('Profile saved');
Route before a request can start:
await page.route('**/api/recommendations', async route => {
await route.fulfill({
status: 503,
contentType: 'application/json',
body: JSON.stringify({ message: 'Service unavailable' }),
});
});
Observation proves actual browser traffic. Routing creates a controlled UI condition. APIRequestContext avoids browser cost for service combinations and data lifecycle. The Playwright API testing guide expands these layer choices.
6. Connect Authentication to Test Data Isolation
A mature answer separates authentication coverage from authentication setup. Keep a few UI tests for login, logout, validation, session expiry, and role behavior. For unrelated scenarios, use a supported API or setup project to create storage state.
// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
import path from 'node:path';
const authFile = path.join(__dirname, '../playwright/.auth/user.json');
setup('authenticate test user', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email')
.fill(process.env.E2E_USER_EMAIL ?? '');
await page.getByLabel('Password')
.fill(process.env.E2E_USER_PASSWORD ?? '');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL(/\/dashboard$/);
await page.context().storageState({ path: authFile });
});
A project can depend on this setup and load storageState. The file can contain cookies or local storage that authorize an account, so keep it outside source control and restrict its lifetime.
Shared login state does not isolate server data. If parallel tests change the same cart, profile, or permissions, independent browser contexts cannot prevent collisions. Use one account per worker, unique entities per test, isolated tenants, or deterministic reset APIs.
For multi-role workflows, create separate browser contexts and state files for buyer, approver, and administrator. Keep role boundaries visible in the test.
7. Discuss Parallelism, Retries, CI, and Evidence
Playwright uses worker processes. Test files run in parallel by default, while tests within one file are sequential by default unless parallel behavior is configured. fullyParallel allows broader test-level parallelism. Projects represent browsers, devices, roles, or other configurations. Sharding splits the suite across machines.
Parallelism is safe only when data and resources are isolated. More workers can overload the application, exhaust accounts, or expose hidden order dependence. Measure the bottleneck and protect unique state.
Retries rerun failed tests in fresh workers and categorize results as passed, flaky, or failed. They can contain disruption and collect artifacts, but a passing retry is still evidence of instability. Track and fix first-attempt failures.
Use traces on first retry, screenshots on failure, and video only when its diagnostic value justifies storage. Trace Viewer can show actions, DOM snapshots, network, console, source, and timing around the failure.
CI should install locked dependencies, install matching browsers and system dependencies, run against a known application build, and preserve reports. See Playwright CI best practices for pipeline design.
8. Answer top playwright interview questions With Engineering Judgment
For scenario questions, state the user or product risk before the API. If a Save test is flaky, do not immediately propose a longer timeout. Ask whether the locator is ambiguous, the listener is late, data is shared, the product response is delayed, or the environment is saturated. Name the evidence you would inspect.
Use tradeoff language:
- "I choose a role locator because the accessible name is a user-facing contract. I use a test ID for a domain object whose text changes."
- "I create data through the API to reduce setup cost, but I retain focused browser coverage for the creation form."
- "I mock the third-party failure for deterministic UI coverage, then keep a smaller real integration check."
- "I use worker scope only because the resource is immutable during tests."
- "I enable retries for evidence and containment, while first-attempt failure remains actionable."
Prepare three stories: a difficult flake, a framework design decision, and a CI improvement. Quantify only with evidence you actually collected. A credible explanation of why you rejected an option often signals more experience than a long tool list.
Interview Questions and Answers
Questions 1-10: Foundations
1. What is Playwright?
Playwright is a browser automation library with APIs for Chromium, Firefox, and WebKit. The Node.js package includes Playwright Test, a runner with fixtures, projects, parallel workers, retries, reporters, traces, and web-first assertions. I use it for browser workflows, API-assisted setup, and cross-browser risk coverage. It is not a substitute for unit, contract, accessibility, or performance testing.
2. What is the difference between Playwright Library and Playwright Test?
Playwright Library provides browser automation objects such as Browser, BrowserContext, Page, Locator, Request, and Response. Playwright Test is the TypeScript and JavaScript test runner built around that library. It adds test discovery, fixtures, expect assertions, projects, retries, workers, sharding, reporters, and configuration. In Python, Java, or .NET, teams use the library with a language-appropriate runner rather than the Node.js Playwright Test runner.
3. Which browsers does Playwright support?
Playwright automates Chromium, Firefox, and WebKit engines with browser builds aligned to the installed package. It can also run branded Chrome and Edge channels where appropriate. Coverage should follow supported-user data and feature risk, not the goal of running every test everywhere. I keep critical workflows across required engines and use a smaller browser set for fast pull request feedback when release policy allows it.
4. What are Browser, BrowserContext, and Page?
Browser represents the launched browser process. BrowserContext is an isolated session with its own cookies, storage, permissions, and pages. Page represents one tab or popup. Playwright Test normally gives each test an isolated context and page, which reduces cross-test leakage. Multiple contexts in one test are useful for multi-user scenarios because they model separate sessions without launching several browser processes.
5. What is a Locator?
A Locator is a reusable description of how to find one or more elements. It resolves against the current DOM when an action or assertion runs, so it handles re-rendered elements better than a stored element handle. Locators support scoping, filtering, chaining, actionability checks, and retrying assertions. I prefer user-facing locators and make action targets unique.
6. What is Playwright auto-waiting?
Before actions such as click or fill, Playwright performs the relevant actionability checks, including conditions such as visibility, stability, ability to receive events, and enabled state. The exact checks depend on the action. Auto-waiting removes many manual waits, but it does not know the business postcondition, repair shared data, or catch an event listener registered too late. I follow actions with web-first assertions.
7. What are web-first assertions?
Assertions such as expect(locator).toBeVisible() and toHaveText() repeatedly evaluate the locator until the condition passes or the assertion times out. They are designed for asynchronous UI updates. In contrast, an immediate value assertion on await locator.textContent() captures one moment and can race rendering. I use web-first assertions for observable UI state and direct assertions for stable API values.
8. What is strictness in Playwright locators?
An operation that implies one target, such as click, fails if the locator matches multiple elements. Strictness prevents Playwright from guessing. I fix it by scoping to a region, row, dialog, or other meaningful container, or by refining the accessible name. first(), last(), and nth() are appropriate only when order itself is the requirement, not as a shortcut for ambiguity.
9. How is Playwright different from Selenium?
Both automate browsers, but their architecture, APIs, language ecosystems, waiting models, and tooling differ. Playwright provides browser contexts, locator-first APIs, network routing, tracing, and a Node.js test runner in one ecosystem. Selenium has broad language and grid maturity and uses the WebDriver standard. I choose based on product browsers, team language, infrastructure, existing investment, and required integrations rather than claiming one tool always wins.
10. What is the recommended locator priority?
I start with getByRole and an accessible name, then labels for form fields, followed by other user-facing attributes such as placeholder, text, alt text, and title. A deliberate test ID is useful for stable domain objects without a strong semantic locator. CSS is valid when DOM structure matters. I avoid long CSS chains and XPath because they couple tests to implementation details and are harder to review.
Questions 11-20: Locators, Pages, and Interactions
11. How do you locate an item in a specific table row?
I locate the table or row by a stable user-facing value, then scope the action inside it. For example, page.getByRole('row').filter({ hasText: 'INV-42' }).getByRole('button', { name: 'Approve' }). This expresses the relationship and avoids a global nth index. I assert the row's updated status after the action.
12. When do you use getByTestId?
I use it when the element is a meaningful domain object but text, role, or accessible name cannot identify it stably. Examples include a chart point, virtualized card, or row whose visible content is intentionally variable. Test IDs should describe business identity, not layout. I do not add them to replace missing accessible names on interactive controls.
13. How do you handle an iframe?
I use page.frameLocator() to scope locators within the frame, then interact with normal locator APIs. I identify the frame by a stable selector or attribute and assert the framed UI outcome. For cross-origin frames, Playwright can still automate through frame APIs, but private third-party DOM or network details may be brittle. I prefer the integration's public visible contract.
14. How does Playwright handle Shadow DOM?
Playwright locators generally pierce open shadow roots, so role, text, and CSS locator strategies can reach elements without manually traversing shadowRoot. XPath does not pierce shadow roots, and closed shadow roots are not accessible. I still scope to the custom component when useful. If a closed component exposes no testable user contract, I test through its public behavior.
15. How do you handle a new tab or popup?
I register the popup event promise before the action, click, then await the popup and assert it. For example, const popupPromise = page.waitForEvent('popup'); await link.click(); const popup = await popupPromise. Any later response wait belongs on the popup page. Registering after the click can miss a fast event.
16. How do you handle browser dialogs?
If no listener is attached, Playwright automatically dismisses dialogs. When the scenario requires accepting, dismissing, or checking the message, I register page.once('dialog', handler) before the triggering action. The handler must resolve the dialog because an open dialog blocks page execution. I avoid permanent listeners that accept unrelated dialogs and hide defects.
17. How do you upload files?
For a normal file input, I call locator.setInputFiles() with a path, paths, or in-memory file payload. If the input is created only after clicking, I register page.waitForEvent('filechooser') before the click and call setFiles on the FileChooser. I verify the application result, such as filename, preview, validation, or successful upload, not just the input action.
18. How do you test downloads?
I register page.waitForEvent('download') before clicking the download control, await the Download, and inspect suggestedFilename(). I call saveAs() into a test output path when content needs validation. I do not depend on a user's Downloads folder. If server headers or response bytes matter, I may also observe the network response.
19. How do you test drag and drop?
I start with sourceLocator.dragTo(targetLocator) and assert the durable outcome, such as moved item and saved state. For widgets needing intermediate movement, I use supported drag options or precise mouse control based on live bounding boxes. File or external data drop is a different contract. I avoid force unless evidence shows actionability is not part of the requirement.
20. How do you avoid hard waits?
I wait on the signal that makes the requirement true: a locator assertion, a specific request or response, URL change, download, popup, or application status. page.waitForTimeout is useful only during diagnosis. Fixed sleeps guess timing, slow fast runs, and still fail under load. If no observable signal exists, I ask whether the product needs better user feedback or testability.
Questions 21-30: Fixtures, Architecture, and Data
21. What is a Playwright fixture?
A fixture supplies a typed dependency to a test and owns its setup and teardown lifecycle. In an extended fixture, code before await use(value) is setup and code after it is teardown. Fixtures can depend on other fixtures and have test or worker scope. I use them for authenticated contexts, API clients, isolated entities, and resources with meaningful cleanup.
22. What is the difference between test-scoped and worker-scoped fixtures?
A test-scoped fixture is created for each test, which favors isolation and simple cleanup. A worker-scoped fixture is shared by tests running in one worker and can reduce expensive setup. Sharing also creates coupling, so I use worker scope only for immutable or safely partitioned resources. A mutable cart or account is usually test-scoped or unique per worker.
23. When would you use beforeEach instead of a fixture?
I use beforeEach for concise setup that is local to one describe block and does not need to expose a typed value or reusable lifecycle. I choose a fixture when setup represents a dependency, needs teardown, composes with other resources, or belongs across files. I avoid placing large invisible navigation and data mutation sequences in every hook because failures become harder to attribute.
24. How do you design a page object model?
I create small page or component objects that expose domain actions and stable locators. I prefer composition, such as Header, CartPanel, and CheckoutPage, over deep inheritance. I do not wrap every Playwright method with clickElement or waitForElement. Assertions stay in tests unless a method has an invariant postcondition that every caller needs.
25. When is a page object unnecessary?
A unique, short workflow can be clearer inline. Abstraction is justified by meaningful repetition, shared component behavior, or a stable domain interface, not by a goal to move every locator into a class. I wait until the shape is understood, then extract at the boundary that lowers change cost. Premature objects often create generic wrappers and hidden waits.
26. How do you create test data?
I prefer supported APIs, factories, or seeded fixtures because they are faster and more deterministic than creating every precondition through the UI. Each test owns a unique entity or isolated tenant and cleanup targets only that data. I keep focused UI tests for creation forms. Test-only endpoints must be authenticated, environment-restricted, and impossible to expose as production backdoors.
27. How do you make tests safe for parallel execution?
I remove shared mutable accounts, fixed entity names, order dependence, global cleanup, and common download paths. IDs include a unique test or worker component, and teardown deletes only owned resources. I also check environment capacity because isolated tests can still overload a small service. Running with one worker is a diagnostic, not the final solution to data collisions.
28. How do you test multiple users in one scenario?
I create separate BrowserContexts, often loaded with different storage states, so each actor has independent cookies and local storage. For example, a requester submits an item and an approver sees and approves it in another context. I coordinate through durable application state rather than sharing Page objects. I close contexts in teardown and use isolated scenario data.
29. How do you manage environment configuration?
I read target URLs and non-secret settings from validated environment variables, give safe local defaults where appropriate, and inject secrets through the CI secret store. I fail early for missing required values or disallowed production targets. Configuration chooses the environment, while tests remain portable through baseURL, API clients, and fixtures. I never commit service credentials or authenticated state.
30. How do you review a Playwright framework design?
I evaluate requirement coverage, layer choice, data ownership, fixture scope, locator semantics, synchronization, assertions, teardown, type safety, reporting, and ease of diagnosis. I look for generic wrappers, shared state, swallowed errors, long hooks, and unnecessary browser setup. A good framework makes correct tests easy to write while preserving native Playwright behavior and trace clarity.
Questions 31-40: Network, Authentication, and Reliability
31. How do you wait for an API response caused by a click?
I create page.waitForResponse before the click, matching parsed URL, HTTP method, and operation identity. Then I click, await the saved promise, assert status or body, and verify the UI. I usually assert status after matching so an unexpected 500 fails directly instead of becoming a timeout. The listener-before-trigger ordering removes the race.
32. What is the difference between waitForRequest and waitForResponse?
waitForRequest resolves when the browser issues the request, so it is useful for checking URL, method, headers, or payload. waitForResponse resolves when status and headers arrive and allows body inspection. I select the earliest signal that proves the requirement. Neither method controls traffic, which is the role of routing.
33. How do you mock a network response?
I register page.route or browserContext.route before the request, then call route.fulfill with a realistic status, content type, and body. I use it for deterministic errors, empty states, and difficult boundaries. I keep payloads aligned with the real contract and label the test as controlled UI coverage. Separate integration or contract tests cover the real dependency.
34. How do you test GraphQL calls?
Because many operations share /graphql, I inspect request.postDataJSON() and match operationName plus relevant variables. For a response, I check both HTTP status and the GraphQL errors array because 200 can contain operation failure. I avoid matching a full generated query string. Routing can target operations in the same way when controlled payloads are needed.
35. How do you perform API testing with Playwright?
I use APIRequestContext through the request fixture or a configured request context. It supports HTTP methods, headers, authentication, multipart data, and response inspection. I use it for setup, cleanup, focused API scenarios, or mixed UI and service workflows. Broad input combinations stay at the API layer, while browser tests cover representative integrated user behavior.
36. How do you reuse authenticated state?
I authenticate through a setup project or supported API, save storageState, and configure dependent projects to load it. I keep a few UI login tests. State files can contain authorization material, so they are excluded from source control and created for restricted accounts. Reuse does not solve server-side data conflicts or token expiry, which need separate design.
37. Setup project or globalSetup, which do you prefer?
I usually prefer a setup project because it participates in the test report, uses fixtures, can produce traces, and supports explicit project dependencies. globalSetup is still useful for process-level preparation that does not fit a test project. The choice follows ownership and diagnostics. I do not put all database, auth, and environment work into one opaque global function.
38. What causes flaky Playwright tests?
Common causes include shared data, ambiguous locators, late event listeners, product races, animations, environment overload, unstable dependencies, expired authentication, incorrect assertions, and hidden order dependence. I reproduce the focused failure, inspect traces and logs, compare passing and failing runs, classify the cause, implement the smallest causal fix, and repeat. A retry does not close the defect.
39. How do retries work?
When a test fails, Playwright discards that worker process and uses a fresh worker for retries or subsequent work. Results are categorized as passed, flaky, or failed. Retries can gather evidence and reduce pipeline disruption, but they increase execution and can hide instability if teams ignore flaky status. I monitor first-attempt failures and keep tests isolated for independent retries.
40. How do you debug a test that passes locally and fails in CI?
I compare application build, environment variables, browser package and binaries, OS dependencies, viewport, locale, fonts, time zone, network, CPU, workers, and test data. I inspect trace, screenshot, video if retained, console, and server logs. Then I reproduce with the same container or CI command. I do not immediately add a sleep or increase all timeouts.
Questions 41-50: Scale, CI, and Senior Scenarios
41. How does Playwright parallelism work?
Playwright Test runs work in independent OS worker processes, each with its own browser. Files are parallel by default, while tests in one file are sequential unless configured otherwise. fullyParallel expands test-level parallelism. Workers improve feedback only when the application, data, and CI machine can support them. I tune workers from evidence and keep tests isolated.
42. What are Playwright projects?
Projects are named configurations that can represent browser engines, devices, locales, roles, environments, or setup dependencies. They share the overall config but can override use options, retries, timeouts, testMatch, and other project settings. I avoid a combinatorial matrix. Each project should map to user risk or test lifecycle, and project names should make reports understandable.
43. What is sharding?
Sharding divides the test suite across separate machines with the command-line form --shard=1/4, --shard=2/4, and so on. It differs from workers, which parallelize inside one machine. Sharding reduces wall-clock time but requires each shard to have the same build, dependencies, configuration, and isolated data. Reports should be merged or published coherently.
44. When would you use serial mode?
Only when a group is intentionally dependent and cannot reasonably be isolated, such as a long stateful certification flow. Serial mode means later tests may be skipped after a failure and the group retries together, which weakens diagnosis and parallelism. I first try to express the flow as one test with steps or give each test independent setup. Serial is not a flake fix.
45. How do you configure Playwright in CI?
I install dependencies from the lockfile, install browser binaries with required system dependencies, start or target a known application build, inject secrets at runtime, and run the chosen projects and workers. I fail on test.only and retain HTML reports and failure evidence. I separate service startup failures from browser failures and use sharding only after data isolation is proven.
46. How do you use Trace Viewer?
I configure trace: 'on-first-retry' for routine CI evidence or trace on for a focused reproduction. Trace Viewer shows action logs, timing, DOM snapshots, locator state, network activity, console messages, and source around each step. I compare the first failure with a passing attempt. A trace helps find cause, but I still verify the fix with repeated execution.
47. How do you perform visual testing?
I use expect(page).toHaveScreenshot() or locator screenshot assertions for stable, high-value surfaces. Baselines are reviewed and maintained per relevant project and environment. I control fonts, viewport, animations, data, time, and OS image because these affect pixels. I set tolerances deliberately and keep functional assertions, since a visual snapshot cannot prove all behavior or accessibility.
48. How do you approach accessibility testing?
I start with accessible product markup and role or label locators, which expose many missing-name and semantic issues during normal automation. I add automated scans such as axe for selected pages and components, then retain keyboard, focus, screen-reader, contrast, and human evaluation where required. Automated rules catch only part of accessibility. Failures need triage, ownership, and regression coverage.
49. How do you test responsive and mobile behavior?
I configure projects with Playwright device descriptors or explicit viewport, user agent, touch, and scale settings. Emulation is useful for layout, input, and browser-context behavior but is not a physical-device replacement. I choose representative breakpoints and critical journeys rather than multiplying every test by every device. Real-device checks cover hardware, browser shell, and platform-specific risk.
50. Design a reliable checkout test and explain your choices.
I create a unique cart or order through an API, open checkout with an isolated authenticated context, and use role or label locators for shipping and payment controls. I register the order response wait before submission, assert exact creation semantics, and verify confirmation plus persisted order state. Payment-provider failures receive controlled route tests, while a smaller real integration check protects the contract. Cleanup owns only this test's data, and CI retains trace evidence on retry.
Common Mistakes
- Memorizing Playwright definitions without a project example or tradeoff.
- Claiming auto-waiting solves all timing and data problems.
- Using CSS or XPath chains when a user-facing locator exists.
- Calling first() to hide an ambiguous action target.
- Storing an ElementHandle across a re-render instead of using a Locator.
- Registering response, popup, download, or file chooser waits after the trigger.
- Putting success status in a response predicate and hiding server errors as timeouts.
- Building a base page that wraps every Playwright method.
- Sharing one mutable account across parallel tests.
- Using worker-scoped fixtures only to make setup faster.
- Saving cookies, storage state, or credentials in source control.
- Mocking every service and calling the suite end-to-end.
- Treating retries as a completed flake fix.
- Increasing global timeouts before reading traces and server logs.
- Enabling maximum workers without checking data and service capacity.
- Using serial mode to mask order dependence.
- Running every browser and device permutation without risk prioritization.
- Quoting fabricated coverage, speed, or flake improvements.
- Describing only what the team did without stating personal ownership.
- Giving an API answer before clarifying the product behavior being tested.
Conclusion
The top playwright interview questions are tests of engineering judgment as much as Playwright knowledge. Strong candidates connect locators, fixtures, contexts, network APIs, parallel execution, and CI to reliability, user risk, and clear evidence.
Practice the 50 answers aloud, but replace generic examples with three detailed stories from your work. Build the small reference project, inspect its trace, run it in parallel, and explain one design you would change at larger scale. That preparation makes answers concise, technically credible, and genuinely yours.
Interview Questions and Answers
What is Playwright?
Playwright is a browser automation library supporting Chromium, Firefox, and WebKit. Its Node.js ecosystem includes Playwright Test with fixtures, projects, parallel workers, retries, reporters, traces, and web-first assertions. I use it as one layer in a broader quality strategy.
What is the difference between Playwright Library and Playwright Test?
The library provides browser automation objects such as Browser, BrowserContext, Page, and Locator. Playwright Test is the TypeScript and JavaScript runner that adds discovery, fixtures, assertions, projects, retries, workers, sharding, configuration, and reporting. Other language bindings normally use their own test runners.
What is a Locator and why is it preferred?
A Locator is a reusable element query that resolves against the current DOM for each action or assertion. It works with actionability, scoping, filtering, strictness, and retrying assertions. This is safer across re-renders than retaining a stale element reference.
How does Playwright auto-waiting work?
Locator actions wait for their relevant actionability conditions, such as visibility, stability, receiving events, and enabled state. Locator assertions independently retry their expected condition. Auto-waiting does not replace business assertions, fix shared state, or repair a listener registered after an event.
How do you choose a locator?
I start with role and accessible name, then label and other user-facing attributes. I use an intentional test ID for domain objects without a stable semantic locator. I scope to meaningful containers and avoid CSS or XPath chains tied to layout.
What is strictness?
Actions that require one element fail when a locator resolves to several. Playwright refuses to guess. I refine or scope the locator instead of using first() unless order is explicitly part of the requirement.
What is a Playwright fixture?
A fixture provides a typed dependency and owns setup and teardown around await use(value). Fixtures can depend on each other and use test or worker scope. I use them for resources with a meaningful lifecycle, such as authenticated contexts, API clients, and isolated entities.
Test-scoped or worker-scoped fixture?
Test scope favors isolation and is the default for mutable resources. Worker scope can reduce expensive setup but shares one resource among tests in a worker. I use worker scope only when sharing is safe, partitioned, and cleanup remains deterministic.
How do you design page objects?
I use small domain or component objects with typed locators and meaningful actions. I prefer composition over deep inheritance and preserve native Playwright semantics. Simple unique workflows can stay inline, and generic click or wait wrappers are avoided.
How do you wait for a response caused by a click?
I create a narrowly matched page.waitForResponse promise before the click, perform the click, then await the promise. I assert response status or data and the visible UI outcome. Matching status after identity keeps unexpected server errors visible.
When do you use routing?
I use page.route or browserContext.route to control traffic for deterministic errors, boundaries, or dependency behavior. I register routes before requests can start and keep payloads contract-compatible. I retain separate coverage for real integrations.
How do you test GraphQL?
I match the shared endpoint by operationName and relevant variables from postDataJSON. I assert both HTTP status and GraphQL errors because a 200 response can still represent failure. I avoid matching full generated query text.
How do you reuse authentication?
I keep focused UI authentication tests, then create storage state through a setup project or supported API for unrelated scenarios. Auth files are sensitive and excluded from version control. Separate accounts, roles, expiry, and server-side data isolation are handled deliberately.
What causes flaky Playwright tests?
Frequent causes include shared data, ambiguous locators, late listeners, product races, environment load, unstable dependencies, expired auth, and incorrect assertions. I reproduce, inspect traces and logs, classify cause, implement the smallest causal fix, and repeat. Retries are containment and evidence, not closure.
How do retries work?
After failure, Playwright discards the worker process and runs retry work in a fresh worker. Outcomes are passed, flaky, or failed. I use bounded retries to collect evidence while tracking first-attempt failure as actionable quality debt.
How do you make tests parallel-safe?
Each test owns unique data, accounts or tenants are partitioned, cleanup targets only owned entities, and paths are unique. I remove order dependence and global deletes. I also tune workers to environment capacity.
What are Playwright projects?
Projects are named configurations for browsers, devices, roles, locales, setup dependencies, or other test variants. Each project should represent a meaningful risk or lifecycle. I avoid a combinatorial matrix and keep names useful in reports.
How do you debug CI-only failures?
I compare build, environment, browser versions, OS dependencies, viewport, locale, fonts, time zone, network, resources, workers, and data. I inspect trace, console, network, screenshot, and server logs, then reproduce with the same CI image or command.
When should you use serial mode?
Only for an intentionally dependent flow that cannot reasonably be isolated. Serial mode reduces parallelism, skips later work after failure, and retries the group together. I first prefer one test with steps or independent setup.
How would you design a reliable checkout test?
I create unique data through an API, use an isolated authenticated context and semantic locators, register the order response wait before submission, assert creation semantics, and verify confirmation plus persistence. Controlled route tests cover provider failures, while separate integration coverage protects the real contract.
Frequently Asked Questions
What Playwright topics are most important for an SDET interview?
Prioritize locators and strictness, web-first assertions, fixtures, browser contexts, authentication state, network waiting and routing, APIRequestContext, test data, parallelism, retries, traces, projects, and CI. Senior interviews also expect tradeoffs and failure-analysis examples.
How many Playwright interview questions should I prepare?
The 50 questions in this guide cover a broad interview surface. Depth matters more than memorizing a larger list, so connect each major area to a project example and prepare follow-up tradeoffs.
How should I answer scenario-based Playwright questions?
Start with the user or product risk, identify evidence, choose the correct test layer and Playwright API, and explain failure modes. End with how you would verify the solution and what tradeoff remains.
What coding task might appear in a Playwright interview?
A common exercise involves login or stored auth, API-created data, one UI mutation, a stable locator, response synchronization, and a meaningful assertion. You may also be asked to diagnose a flaky test or add route-based error coverage.
Should I compare Playwright and Selenium in an interview?
Be ready to compare architecture, supported languages, browser strategy, waiting model, tooling, and existing ecosystem. Avoid declaring a universal winner, and connect the choice to the team's product and constraints.
How do I demonstrate senior Playwright experience?
Discuss framework boundaries, code review standards, data isolation, authentication security, flake investigation, CI capacity, risk-based browser coverage, and measurable improvements you personally delivered. Include decisions you rejected and why.
Are Playwright API methods enough to pass an interview?
No. Method knowledge is necessary, but interviewers also assess test design, maintainability, debugging, security, communication, and delivery. Explain when an API is appropriate and what it cannot prove.
What should I build for Playwright interview practice?
Build a compact TypeScript suite with a local web server, two projects, a typed fixture, storage-state authentication, API data creation, a response wait, one route mock, parallel-safe data, and CI artifacts. Keep it small enough to explain every line.
Related Guides
- Playwright Scenario-Based Interview Questions and Answers
- Playwright Interview Questions and Answers (2026 Guide)
- Playwright Interview Questions for 2 Years Experience (2026)
- Playwright Interview Questions for 3 Years Experience (2026)
- Playwright Test Runner Interview Questions and Answers
- Cypress Interview Questions and Answers (2026)