50 Playwright Interview Questions & Answers (2026 Guide)
50 Playwright interview questions with clear answers and TypeScript code — locators, auto-waiting, fixtures, config, network mocking, API testing, CI and debugging.
Playwright has become the fastest-growing automation tool in Indian QA hiring. Today, a large share of new automation openings list Playwright next to (or instead of) Selenium — especially product companies, startups and service firms modernising their frameworks.
This guide gives you 50 Playwright interview questions in five groups: basics, locators and waiting, the test runner and config, advanced topics (network, auth, API) and framework/CI design. Code is in TypeScript, the most common choice in job descriptions. Read the answer, then explain it in your own words with an example from your project.
Playwright basics (1–10)
1. What is Playwright?
Playwright is an open-source end-to-end testing framework from Microsoft. It automates Chromium, Firefox and WebKit with one API, and supports TypeScript/JavaScript, Python, Java and .NET. It ships with its own test runner (@playwright/test), auto-waiting, tracing and parallel execution.
2. Why are companies moving from Selenium to Playwright?
Faster and more stable tests (auto-waiting and web-first assertions remove most flaky waits), one install for all browsers, built-in runner, parallelism, reports, trace viewer, API testing and network mocking. Less boilerplate means a smaller framework to maintain.
3. Which browsers does Playwright support?
Chromium (Chrome, Edge), Firefox and WebKit (the engine behind Safari). It can also run branded Chrome and Edge using the channel option, and emulate mobile devices such as iPhone and Pixel.
4. How do you install Playwright?
Run npm init playwright@latest. It creates playwright.config.ts, an example test, an optional GitHub Actions workflow and downloads the browsers. Browsers can be installed later with npx playwright install.
5. Explain Browser, BrowserContext and Page.
Browser is a launched browser instance. BrowserContext is an isolated session inside it — like a fresh incognito profile with its own cookies and storage. Page is a single tab in a context. The runner gives every test a new context, so tests do not leak state.
6. How do you run tests?npx playwright test runs all tests. Useful flags: --headed, --project=chromium, --grep @smoke, --workers=4, --ui for UI mode and --debug to step through with the Inspector.
7. What is headless mode? Is it default?
Headless runs the browser without a visible window; it is faster and is the default in Playwright. Use --headed or headless: false in config when you want to watch the run.
8. What is Codegen?npx playwright codegen https://example.com opens a browser and records your actions as test code with recommended locators. It is useful to discover locators quickly, but the output should be refactored into page objects before it goes into the framework.
9. Write a basic Playwright test.
A test uses the page fixture and web-first assertions:
import { test, expect } from '@playwright/test';
test('user can log in', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('qa@test.com');
await page.getByLabel('Password').fill('Secret@123');
await page.getByRole('button', { name: 'Login' }).click();
await expect(page).toHaveURL(/dashboard/);
await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible();
});10. Which languages does Playwright support, and which is most used?
TypeScript/JavaScript, Python, Java and C#. The full test runner features (fixtures, projects, sharding, UI mode) are in the Node.js version, so TypeScript is the most common choice in Indian job descriptions; Java and Python teams usually pair Playwright with TestNG/JUnit or pytest.
Locators, auto-waiting and assertions (11–20)
11. What are locators in Playwright?
A Locator is a lazy, re-evaluated way to find elements. It is resolved every time an action runs, so it does not go stale like a Selenium WebElement. Locators are created with page.getByRole(), getByText(), getByLabel(), getByPlaceholder(), getByAltText(), getByTitle(), getByTestId() or page.locator() for CSS/XPath.
12. Which locator strategy does Playwright recommend?
User-facing locators first: getByRole with an accessible name, then getByLabel, getByText and getByTestId. They mirror how users find elements and survive UI refactors. CSS and XPath are a fallback for elements with no accessible role.
13. What is auto-waiting?
Before an action, Playwright waits until the element is attached, visible, stable (not animating), able to receive events and enabled (and editable for fill). This removes the need for most explicit waits and sleep calls.
14. What are web-first assertions?
Assertions like await expect(locator).toBeVisible(), toHaveText(), toHaveValue(), toHaveCount() and expect(page).toHaveURL() automatically retry until the condition passes or the timeout (5 seconds by default) expires. Always prefer them to reading a value and comparing it manually.
15. What is strict mode in locators?
If a locator used for an action matches more than one element, Playwright throws an error instead of clicking the first one. Fix it by making the locator more specific, or by using .first(), .last(), .nth(i) or .filter() intentionally.
16. How do you filter and chain locators?
Chain to search within a parent and use filter to narrow results:
const row = page.getByRole('row').filter({ hasText: 'Order #1042' });
await row.getByRole('button', { name: 'Cancel' }).click();
// item that contains a child element
page.locator('.product').filter({ has: page.getByText('In stock') });17. How do you handle iframes?
Use page.frameLocator('#payment-frame') (or locator.contentFrame()) and then locate inside it, for example page.frameLocator('#payment-frame').getByLabel('Card number').fill('4111...'). No switching back is needed as in Selenium.
18. How do you handle a new tab or popup window?
Start waiting for the event before the click that opens it:
const popupPromise = page.waitForEvent('popup');
await page.getByText('Open invoice').click();
const popup = await popupPromise;
await popup.waitForLoadState();
await expect(popup).toHaveTitle(/Invoice/);19. How do you handle alerts, confirms and prompts?
Register a dialog handler before the action: page.once('dialog', d => d.accept()). Use d.message() to assert the text, d.dismiss() to cancel and d.accept('text') for prompts. By default Playwright dismisses dialogs automatically.
20. What are soft assertions?expect.soft() records a failure but lets the test continue, so you see all mismatches in one run (useful on forms with many fields). The test is still marked failed at the end.
Test runner, fixtures and configuration (21–30)
21. What does playwright.config.ts contain?
Global settings: testDir, timeout, retries, workers, fullyParallel, reporter, and a use block (baseURL, headless, viewport, trace, screenshot, video). It also defines projects to run the same tests on different browsers or devices.
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
retries: process.env.CI ? 2 : 0,
reporter: [['html'], ['junit', { outputFile: 'results.xml' }]],
use: {
baseURL: process.env.BASE_URL || 'https://staging.example.com',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
{ name: 'mobile', use: { ...devices['Pixel 7'] } },
],
});22. What are fixtures?
Fixtures provide each test with what it needs — built-in ones are page, context, browser, request and browserName. They are set up only when a test asks for them and torn down after. Custom fixtures are created with test.extend(), often to inject page objects or logged-in pages.
import { test as base } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';
export const test = base.extend<{ loginPage: LoginPage }>({
loginPage: async ({ page }, use) => {
const loginPage = new LoginPage(page);
await loginPage.open();
await use(loginPage);
},
});23. What hooks are available?test.beforeAll, test.beforeEach, test.afterEach and test.afterAll, scoped to a file or a test.describe block. Prefer fixtures for reusable setup; hooks are fine for simple per-file steps.
24. How does parallel execution work?
Test files run in parallel across worker processes. fullyParallel: true also runs tests inside one file in parallel. Control workers with --workers. Use test.describe.configure({ mode: 'serial' }) only for tests that truly depend on each other.
25. What is sharding?
Splitting a suite across multiple machines: npx playwright test --shard=1/4 on four CI agents. Blob reports from each shard can be merged into one HTML report with npx playwright merge-reports.
26. How do you configure retries and why?
Set retries: 2 in config (commonly only on CI) or --retries=2. A test that passes on retry is reported as flaky, which helps you find and fix instability instead of hiding it.
27. What timeouts exist in Playwright?
Test timeout (30 s default), expect timeout (5 s), actionTimeout and navigationTimeout (no limit by default, set in use), and the global timeout for the whole run. Use test.setTimeout() or test.slow() for one long test.
28. How do you tag and filter tests?
Add tags in the title or details: test('checkout', { tag: '@smoke' }, async () => {}). Run with --grep @smoke or exclude with --grep-invert @slow. Annotations test.skip, test.fixme, test.fail and test.only control execution.
29. What reporters are available?
Built-in: list, line, dot, html, json, junit and blob. Teams often add Allure via allure-playwright. Several reporters can be combined.
30. How do you run the same tests in multiple environments?
Read baseURL and credentials from environment variables (with dotenv) and pass them in the use block, or create one project per environment. Never hard-code URLs or passwords in tests.
🚀 Looking for Playwright automation jobs?
QA Jobs India shares 100+ fresh QA & software testing openings every morning — manual, automation, API and remote roles.
See today’s QA jobs →Network, authentication and API testing (31–40)
31. How do you mock an API response?
Use page.route() to intercept a request and return your own data — ideal for testing empty states and error messages:
await page.route('**/api/orders', route =>
route.fulfill({ status: 200, json: [] })
);
await page.goto('/orders');
await expect(page.getByText('No orders yet')).toBeVisible();
// simulate a server error
await page.route('**/api/pay', route => route.fulfill({ status: 500 }));32. How do you block images or third-party scripts?await page.route('**/*.{png,jpg,jpeg}', r => r.abort()) blocks images; abort analytics domains the same way. It speeds up tests and removes noise from external services.
33. How do you wait for a specific API call?
Start waiting before the action: const resp = page.waitForResponse(r => r.url().includes('/api/cart') && r.status() === 200), click, then await resp and assert on (await resp).json().
34. How do you avoid logging in before every test?
Log in once in a setup project, save cookies and local storage with storageState, and reuse it:
// auth.setup.ts
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill(process.env.USER_EMAIL!);
await page.getByLabel('Password').fill(process.env.USER_PASS!);
await page.getByRole('button', { name: 'Login' }).click();
await page.context().storageState({ path: '.auth/user.json' });
});
// playwright.config.ts -> projects
{ name: 'setup', testMatch: /auth\.setup\.ts/ },
{ name: 'chromium', dependencies: ['setup'],
use: { ...devices['Desktop Chrome'], storageState: '.auth/user.json' } },35. How do you do API testing with Playwright?
Use the request fixture (an APIRequestContext). It sends HTTP calls without a browser and shares cookies with the context when needed:
test('create user via API', async ({ request }) => {
const res = await request.post('/api/users', {
data: { name: 'Asha', role: 'tester' },
});
expect(res.status()).toBe(201);
const body = await res.json();
expect(body.name).toBe('Asha');
});36. How do you combine API and UI in one test?
Create test data through the API (fast and reliable), then verify it in the UI, and clean up through the API in afterEach. This keeps UI tests short and focused on what only the UI can prove.
37. How do you upload and download files?
Upload: await page.getByLabel('Resume').setInputFiles('data/cv.pdf'). Download: start page.waitForEvent('download'), click the link, then await download.saveAs('downloads/' + download.suggestedFilename()).
38. How do you test on mobile viewports and devices?
Use device descriptors in a project or test.use({ ...devices['iPhone 14'] }). They set viewport, user agent, touch and device scale factor. It is emulation in desktop engines — real-device testing still needs Appium or a device cloud.
39. How do you set geolocation, locale, timezone or permissions?
Through context options: test.use({ geolocation: { latitude: 18.52, longitude: 73.85 }, permissions: ['geolocation'], locale: 'en-IN', timezoneId: 'Asia/Kolkata' }). Useful for location-based apps and date formatting checks.
40. How does visual testing work in Playwright?await expect(page).toHaveScreenshot('home.png') compares against a stored baseline and fails on pixel differences above the threshold. Update baselines with --update-snapshots, mask dynamic areas with the mask option, and generate baselines on the same OS as CI.
Framework design, CI and debugging (41–50)
41. How do you implement the Page Object Model in Playwright?
Create a class per page that receives page, exposes locators as properties and user actions as methods. Keep assertions in tests (or clearly named expect… methods), and inject page objects through fixtures.
import { Page, Locator } from '@playwright/test';
export class LoginPage {
readonly email: Locator;
readonly password: Locator;
readonly submit: Locator;
constructor(private page: Page) {
this.email = page.getByLabel('Email');
this.password = page.getByLabel('Password');
this.submit = page.getByRole('button', { name: 'Login' });
}
async open() { await this.page.goto('/login'); }
async login(user: string, pass: string) {
await this.email.fill(user);
await this.password.fill(pass);
await this.submit.click();
}
}42. Describe a good Playwright framework structure.tests/ (specs by feature), pages/ (page objects), fixtures/ (custom fixtures), utils/ (API helpers, data builders), test-data/, .env files per environment and playwright.config.ts. Add ESLint, Prettier and a CI workflow, and keep tests independent so they can run in parallel.
43. How do you debug a failing test?
Run npx playwright test --debug to step through in the Inspector, add await page.pause(), use UI mode (--ui) with time-travel, or open the trace of a CI failure. VS Code’s Playwright extension lets you set breakpoints and pick locators.
44. What is the Trace Viewer?
A recorded timeline of a test: every action, DOM snapshots before and after, network calls, console logs and source. Enable with trace: 'on-first-retry' and open with npx playwright show-trace trace.zip or trace.playwright.dev. It is the fastest way to diagnose CI-only failures.
45. How do you run Playwright in CI/CD?
Install dependencies (npm ci), install browsers with npx playwright install --with-deps (or use the official Playwright Docker image), run npx playwright test and publish the HTML report and traces as artifacts. It works with GitHub Actions, Jenkins, GitLab CI and Azure DevOps.
46. How do you reduce flaky tests?
Use role-based locators and web-first assertions, never waitForTimeout, keep tests isolated with their own data, mock unstable third-party calls, wait for specific responses instead of load states, and review tests marked flaky in reports.
47. How do you manage test data?
Generate unique data per test (timestamps or faker), create it via API in fixtures, and clean up after the test. Keep static data in JSON files, and secrets in environment variables or CI secrets — never in the repository.
48. Selenium vs Playwright — what would you say in an interview?
Selenium is mature, W3C standard, supports many languages and real browsers through drivers, and has a huge ecosystem. Playwright talks to browsers directly, has auto-waiting, a built-in runner, tracing, network mocking and API testing. For new web projects Playwright is often faster to build and more stable; Selenium remains common in existing Java frameworks. See our Selenium vs Playwright comparison.
49. What are the limitations of Playwright?
No support for native mobile apps or desktop apps, no legacy browsers like IE, and full runner features are Node.js-first. Very new compared with Selenium, so some enterprise grids and tools still assume WebDriver.
50. Explain your Playwright framework in 60 seconds.
A sample answer: “Our framework uses Playwright with TypeScript and the Page Object Model. Page objects are injected through custom fixtures; login is done once in a setup project using storageState. Test data is created via API helpers. We run tests in parallel on Chromium and WebKit in GitHub Actions, sharded across 4 machines, with retries on CI, HTML and Allure reports, and traces on first retry for debugging.”
How to prepare for a Playwright interview
- Build one small project: a login, search and checkout flow on a demo site, with page objects, fixtures, API setup and a GitHub Actions run. Put it on GitHub and add the link to your resume.
- Practise explaining locators, auto-waiting and storageState with examples — these three come up in almost every interview.
- Be ready to compare Selenium and Playwright honestly, without dismissing either.
- Revise JavaScript/TypeScript basics: async/await, promises, arrow functions, classes and array methods.
- Use our QA cheat sheets for last-minute revision of Playwright commands.
FAQs
Is Playwright good for freshers?
Yes. It is easier to start with than Selenium because waits, the runner and reports are built in. Learn JavaScript or TypeScript basics first, then Playwright.
Should I learn Selenium or Playwright in 2026?
If you are targeting service companies with existing Java frameworks, Selenium with Java is still essential. For product companies and new projects, Playwright is in high demand. Many testers learn Selenium first and add Playwright.
Which language should I use with Playwright?
TypeScript is the most popular in job descriptions. Java and Python bindings are also used, especially in teams that already have Java or Python skills.
How many Playwright questions are asked in an interview?
Typically 10–20 in an automation round: locators, waits, config, POM, auth, API and one live coding task such as automating a login or a table filter.
📚 More QA interview question banks
Selenium (60) · Playwright (50) · Manual Testing (60) · API Testing (50) · SQL for Testers (50) · Mobile / Appium (50) · JIRA & Agile (50) — open the all-in-one QA Study Material hub →
💎 Get every QA opening, every day
Join QA Jobs India Premium for 100+ verified QA jobs daily with HR contact details.