Playwright Interview Questions
Master your interview preparation with comprehensive Q&A covering all difficulty levels
How to Ace Your Playwright Interview
Why Playwright Interviews Are Different: Playwright is the modern choice for test automation in 2024+. Interviewers expect understanding of async/await patterns, CDP (Chrome DevTools Protocol), browser contexts, and how it differs from Selenium. They'll dig into your experience with complex scenarios, performance optimization, and multi-browser testing.
Critical Topics Interviewers Always Ask:
- Playwright Architecture: How it differs from Selenium, CDP under the hood, browser launch process
- Async/Await Patterns: Promise handling in JavaScript/TypeScript, how Playwright leverages async
- Auto-Wait Strategy: Playwright's built-in waiting vs Selenium's manual waits, reliability advantages
- Browser Contexts & Sessions: Test isolation, cookie/storage management, multi-tenant testing
- API Testing with Playwright: Built-in API testing, mock server setup, request interception
- Cross-Browser Testing: Chromium, Firefox, WebKit differences, parallel execution strategies
Key Interview Mistakes:
- ❌ Not understanding Playwright's auto-wait mechanism (biggest advantage over Selenium)
- ❌ Confusing Playwright with just a Selenium alternative (it's fundamentally different)
- ❌ Not mentioning TypeScript support or async/await patterns
- ❌ Treating it like traditional page object pattern without considering fixtures
- ❌ Missing the API testing and network interception capabilities
How to Answer: Always emphasize modern web testing practices. Playwright is built for contemporary applications (SPAs, Progressive Web Apps, micro-frontends). Show understanding of DevOps integration, CI/CD pipelines, and cloud-scale testing.
Playwright Interview Questions - Beginner Level
What is Playwright and what are its main features?
Playwright is a Node.js library for automating browsers developed by Microsoft. Main features: supports Chromium, Firefox, WebKit; fast execution; built-in debugging; native async/await; API testing capabilities; cross-browser testing; powerful selectors; auto-waiting for elements.
How is Playwright different from Selenium?
Playwright: modern, faster, native async/await, built-in auto-wait, direct DevTools Protocol, API testing support, better multi-browser support. Selenium: older, wider language support, larger community, requires WebDriver server, manual wait handling.
What languages does Playwright support?
JavaScript/TypeScript (primary), Python, C# (.NET), Java. Each with native API and similar functionality. TypeScript is recommended for type safety and IDE support.
How do you install and set up Playwright?
npm install -D @playwright/test. Install browsers: npx playwright install. Create playwright.config.ts for configuration. Set baseURL, timeout, and browser launch options.
How do you launch a browser in Playwright?
const browser = await chromium.launch(); const context = await browser.newContext(); const page = await context.newPage(); Or use test fixtures for auto cleanup.
What are browser context and page in Playwright?
Browser context: isolated browser session with own cookies, storage, cache. Page: single tab/page within context. Multiple pages can share context. Context allows test isolation without launching new browsers.
How do you navigate to a URL in Playwright?
await page.goto('https://example.com'); With timeout: await page.goto(url, { timeout: 30000 }); With waitUntil: await page.goto(url, { waitUntil: 'networkidle' });
How do you find elements in Playwright?
page.locator('selector'): CSS/XPath selector. page.getByRole('button'): ARIA role. page.getByText('text'): by visible text. page.getByPlaceholder('placeholder'): by placeholder. These auto-wait for elements.
What is auto-waiting in Playwright?
Playwright automatically waits for elements to be visible, enabled, and stable before action (click, fill, etc.). Configurable via timeout in config. Eliminates manual waits in most cases. Major advantage over Selenium.
How do you interact with elements in Playwright?
await page.locator('selector').click(); .fill('text'): type text. .press('Enter'): press key. .select('value'): select dropdown. .check(): check checkbox. .tap(): touch input.
How do you get element text in Playwright?
const text = await page.locator('selector').textContent(); Or: await page.locator('selector').innerText(); textContent includes hidden text, innerText is visible only.
How do you handle assertions in Playwright?
Use expect() from @playwright/test: expect(locator).toBeVisible(); expect(text).toBe('value'); expect(url).toContain('path'); Auto-retries assertions for flakiness.
How do you handle dropdowns in Playwright?
await page.locator('select').selectOption('value'); Or by label: selectOption({ label: 'text' }); For custom dropdowns: click, then click option.
How do you handle checkboxes and radio buttons?
Check: await page.locator('input[type=checkbox]').check(); Uncheck: .uncheck(); Is checked: await page.locator(selector).isChecked(); Radio: .check() selects only that button.
How do you upload files in Playwright?
await page.locator('input[type=file]').setInputFiles('/path/to/file'); For multiple: setInputFiles(['/path1', '/path2']); Clear files: setInputFiles([]);
How do you handle alerts and dialogs?
page.on('dialog', dialog => { dialog.accept() }); Or: dialog.dismiss(); For input: dialog.accept('text'); For checking: alert.type, alert.message
How do you handle navigation (back, forward, reload)?
await page.goBack(); await page.goForward(); await page.reload(); Each has options like waitUntil for network conditions.
How do you take screenshots in Playwright?
await page.screenshot({ path: 'screenshot.png' }); Full page: { fullPage: true }; Mask elements: { mask: [locator] }; For comparison: omit path for buffer.
How do you handle keyboard events in Playwright?
await page.keyboard.press('ArrowDown'); page.keyboard.type('text'); press(key) for single key. type(text) for string. Can chain: press('Control+A')
How do you execute JavaScript in Playwright?
const result = await page.evaluate((arg) => { return document.title; }); Pass args: evaluate(({ val }) => val + 1, { val: 10 });
How do you scroll in Playwright?
await page.locator('selector').scrollIntoViewIfNeeded(); Or: page.evaluate(() => window.scrollBy(0, 100)); Scroll to element: page.locator(selector).focus()
How do you get attributes in Playwright?
const attr = await page.locator('selector').getAttribute('attribute-name'); For all attributes: locator.evaluate(el => el.attributes)
How do you check element visibility and enabled state?
const visible = await page.locator('selector').isVisible(); const enabled = await page.locator('selector').isEnabled(); const checked = await page.locator('selector').isChecked();
What is the test fixture in Playwright?
Fixtures: reusable setup/teardown. Default: page, browser, context. Custom: extend base fixtures. Scoped: test, worker. Auto-cleanup after test.
How do you structure a basic Playwright test?
import { test, expect } from '@playwright/test'; test('name', async ({ page }) => { await page.goto('url'); await expect(locator).toBeVisible(); });
Playwright Interview Questions - Intermediate Level
How do you wait for elements in Playwright?
Playwright auto-waits. Manual wait: await page.waitForSelector('selector'); waitForNavigation(); waitForFunction(() => condition); Most waits are implicit via actions.
What is locator and why is it better than page.$()?
Locator: lazy, chainable, auto-retrying, auto-waiting. page.$: eager, returns element or null. Locators are modern approach: page.locator('selector').locator('child')
How do you use getByRole for accessible selectors?
page.getByRole('button', { name: 'Submit' }); Supports: 'button', 'textbox', 'checkbox', 'radio', 'link', etc. Encourages accessible markup testing.
How do you handle iframes in Playwright?
const frameHandle = await page.$('iframe'); const frame = await frameHandle.contentFrame(); Or: page.frameLocator('iframe').locator('selector'); Frame locators auto-wait for frame attachment.
How do you handle shadow DOM in Playwright?
Playwright pierces shadow DOM by default: page.locator('pierced >> selector'). Or use evaluate: evaluate(() => el.shadowRoot?.querySelector())
How do you intercept and mock network requests?
await page.route('**/api/**', route => { route.abort(); }); route.continue(); route.fulfill({ status: 200, body: 'text' }); Great for testing error scenarios.
How do you handle API testing in Playwright?
const response = await page.request.get('url'); const json = await response.json(); Check: response.status(), response.ok(). Built-in API context for non-browser testing.
How do you test multiple browser contexts?
const context1 = await browser.newContext(); const context2 = await browser.newContext(); Each has isolated storage. Useful for multi-user scenarios.
How do you manage cookies in Playwright?
await context.addCookies([{name: 'x', value: 'y'}]); const cookies = await context.cookies(); await context.clearCookies(); Import/export for persistence.
How do you handle localStorage and sessionStorage?
await page.evaluate(() => localStorage.setItem('key', 'value')); Get: page.evaluate(() => localStorage.getItem('key')); Clear: page.evaluate(() => localStorage.clear());
How do you click at specific coordinates?
await page.mouse.click(x, y); Or: page.locator('selector').click({ position: { x: 10, y: 10 } });
How do you handle hover and mouse movements?
await page.mouse.move(x, y); await page.locator('selector').hover(); Can chain: hover().then(click())
How do you perform drag and drop?
await page.locator('source').dragTo(page.locator('target')); Or: mouse.move(), mouse.down(), move(), mouse.up()
How do you run tests in parallel?
Playwright runs in parallel by default. Config: fullyParallel: true; workers: 4; Disable: fullyParallel: false. Each worker isolated.
How do you use global setup and teardown?
Create globalSetup.ts: async function setup() { ... }; export default setup; In config: { globalSetup: '...', globalTeardown: '...' }
How do you create custom fixtures?
export const test = base.extend({ myFixture: async ({ page }, use) => { await use(page); } }); Fixtures can depend on other fixtures.
How do you debug tests in Playwright?
Use: --debug flag. Step through code, inspect DOM, see logs. VS Code extension for inline debugging. page.pause() in test code.
How do you run tests in headed mode?
npx playwright test --headed; Or in config: headless: false; Useful for debugging visually.
How do you use codegen to generate tests?
npx playwright codegen https://example.com; Records actions and generates test code automatically. Good for learning and quick test generation.
How do you cross-browser test with Playwright?
Config projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }, { name: 'firefox', ... }, { name: 'webkit', ... }]
How do you test mobile viewports in Playwright?
Use devices: iPhone 12, Galaxy S9, etc. config: { use: { ...devices['iPhone 12'] } }; Tests mobile layout without separate setup.
How do you filter tests to run specific ones?
npx playwright test test.spec.ts; Match: test.spec.ts:1; By name: npx playwright test -g "login"; Tags: @smoke
How do you retry failed tests?
Config: retries: 2; Or: test.only(); test.skip(); Retry only on failure, not on success.
How do you generate HTML reports?
Config: reporter: 'html'; npx playwright show-report; Reports include traces, screenshots, logs.
What is Playwright Trace and how do you use it?
Trace records: actions, DOM snapshots, screenshots, network logs. Enable: trace: 'on-first-retry'; View: npx playwright show-trace trace.zip
Playwright Interview Questions - Advanced Level
How do you implement Page Object Model (POM) in Playwright?
Create page classes: export class LoginPage { constructor(page) { this.page = page; } async login(user, pass) { ... } }; Use in tests: const login = new LoginPage(page); Modern approach: fixtures instead of POM.
How do you handle complex wait scenarios?
Use waitForFunction: await page.waitForFunction(({ val }) => val === expected, {}, { val }); Or: expect(locator).toHaveCount(expected, { timeout: 30000 })
How do you handle service workers and PWAs?
Test offline: page.context().setOffline(true); Service worker registration: page.evaluate(() => navigator.serviceWorker.controller); Mock service worker responses.
How do you test GraphQL queries with Playwright?
Intercept GraphQL requests: page.route('**/graphql', route => { ... }); Check request body: route.request().postDataJSON(); Mock response: route.fulfill({...})
How do you test WebSocket connections?
page.on('websocket', ws => { ws.on('framereceived', event => { console.log(event.payload); }); }); Hard to mock; consider HTTP alternatives in tests.
How do you implement visual regression testing?
await expect(page).toHaveScreenshot(); Compares with baseline. Use masks to ignore dynamic content. Detect layout/style regressions.
How do you test accessibility with Playwright?
Use getByRole for accessible selectors. Integration with Axe: npm install @axe-core/playwright; Run: expect.toPass() on accessibility checks.
How do you collect performance metrics in Playwright?
const metrics = await page.evaluate(() => window.performance.getEntriesByType('navigation')); Parse: FCP, LCP, CLS, etc. Use with expect() to validate.
How do you use Chrome DevTools Protocol (CDP) with Playwright?
Playwright abstracts CDP, but access via: const cdp = await page.context().newCDPSession(page); Send commands: await cdp.send('Page.setGeolocationOverride', {...})
How do you test geolocation and permissions?
context.grantPermissions(['geolocation']); context.setGeolocation({ latitude: 37.7749, longitude: -122.4194 }); Simulates location without real device.
How do you test with different network conditions?
page.context().route('**/*', route => { setTimeout(() => route.continue(), 100); }); Or CDP: cdp.send('Network.emulateNetworkConditions', {...})
How do you implement BDD with Playwright?
Use Cucumber with TypeScript: npm install @cucumber/cucumber; Write .feature files; Implement step definitions with Playwright locators.
How do you handle authentication flows (OAuth, JWT)?
Store tokens: context.addCookies([{...}]); Or localStorage: page.evaluate(() => localStorage.setItem('token', jwt)); Reuse across tests via fixtures.
How do you implement test data factories?
Create factory functions: export async function createUser(api, data) { return api.post('/users', data); }; Use in tests via fixtures or global setup.
How do you run tests in Docker/containers?
Use mcr.microsoft.com/playwright image. Dockerfile: FROM mcr.microsoft.com/playwright:v1.x; Enables CI/CD without local browser setup.
How do you integrate Playwright with CI/CD pipelines?
GitHub Actions: uses: microsoft/playwright-github-action; npm test; Auto-upload reports. Jenkins/GitLab: similar integration via Docker or native runners.
How do you generate and view test reports?
HTML: reporter: ['html', 'json', 'junit']; View: npx playwright show-report; Include traces, screenshots, videos, timing info.
How do you capture videos of test runs?
Config: video: 'retain-on-failure'; Video saved for failed tests only. Or: video: 'on' for all. Specify size: video: { size: { width: 1280, height: 720 } }
How do you organize tests with tags and annotations?
test.describe.only(); test.skip(); test.fixme(); Annotations: @skip, @smoke. Filter: npx playwright test -g "@smoke"
How do you handle secrets and environment variables?
Use .env files with dotenv: require('dotenv').config(); Or process.env.API_KEY; GitHub Secrets for CI. Never hardcode credentials.
71-150. Advanced Topics (abbreviated)
71-80: Multi-tab/window testing, WebDriver BiDi, remote browser execution, cloud testing platforms, test sharding. 81-90: Custom reporters, test analytics, flakiness detection, test reliability metrics, performance benchmarking. 91-100: Advanced selector strategies, dynamic content handling, real-time collaboration testing, video streaming, complex animations.
101-110: Microservice testing, contract testing, distributed tracing, chaos testing with Playwright, test environment orchestration. 111-120: Monitoring and observability, test result aggregation, failure analysis automation, AI-powered test generation, self-healing tests.
121-130: Enterprise scale testing, test result caching, incremental testing, smart test selection, test maintenance automation. 131-140: Competitive testing, synthetic monitoring, load testing with Playwright, accessibility at scale, performance budgets.
141-150: Future-ready testing patterns, headless browser alternatives, edge computing testing, cross-platform testing strategies, test quality metrics, ROI measurement.