Top 50 Playwright Interview Questions and Answers for Automation Testing

Playwright has quickly become one of the most preferred automation tools in modern QA teams because it combines speed, stability, and clean coding practices. If you are preparing for software testing interviews, understanding Playwright basics is a smart move. In this guide, I have covered the top 50 Playwright interview questions with practical, easy-to-understand answers so you can explain concepts confidently, even if you are transitioning from manual testing.
1. What is Playwright?
Playwright is a free and open source modern automation framework for web testing. It supports Chromium, Firefox, and WebKit with a single API. Teams like it because tests are fast, stable, and easier to maintain.
2. Why do teams choose Playwright for automation?
Playwright offers auto-waiting, powerful locators, parallel execution, and built-in debugging tools. It helps reduce flaky tests when used properly. It also integrates well with CI/CD pipelines.
3. Which browsers are supported in Playwright?
Playwright supports Chromium, Firefox, and WebKit. This lets QA teams validate behavior across major browser engines. It is very useful for cross-browser coverage with one framework.
4. Which languages are supported by Playwright?
Playwright supports JavaScript, TypeScript, Python, Java, and .NET. Many teams prefer TypeScript/JavaScript because of strong test runner support. Language choice depends on team skill and project stack.
5. What is Playwright Test Runner?
Playwright Test Runner is the built-in framework (@playwright/test) for writing and running tests. It supports fixtures, retries, parallel runs, projects, and reports. It removes the need for many external tools.
6. What is a BrowserContext in Playwright?
A BrowserContext is an isolated browser session inside a browser instance. Each context has separate cookies and storage. This helps keep tests independent and clean.
7. Difference between Browser and BrowserContext?
Browser is the top-level browser process. BrowserContext is an isolated profile/session inside that browser. You can run many contexts in one browser to improve test speed and isolation.
8. What is a Page object in Playwright?
A Page represents one tab in the browser. You interact with elements, navigate URLs, and run assertions through it. Most test actions are performed using the page fixture.
A clean way to organize automation code for stability, readability, and easy maintenance.
What Is a Page Object?
A Page Object is a class that keeps page locators and page actions in one place.
Instead of writing raw selectors in every test, you call reusable methods like login(), searchProduct(), or submitOrder().
Why Use It?
- Less code duplication
- Cleaner test files
- Easy locator updates
- Better team collaboration
Best Practice
- Keep assertions in test layer (mostly)
- Keep UI actions in page object
- Use stable locators (role/test-id)
- Use meaningful method names
Example: Login Page Object (TypeScript)
import { Page, Locator } from '@playwright/test';
export class LoginPage {
readonly page: Page;
readonly emailInput: Locator;
readonly passwordInput: Locator;
readonly loginButton: Locator;
readonly errorMessage: Locator;
constructor(page: Page) {
this.page = page;
this.emailInput = page.getByLabel('Email');
this.passwordInput = page.getByLabel('Password');
this.loginButton = page.getByRole('button', { name: 'Login' });
this.errorMessage = page.getByTestId('login-error');
}
async goto() {
await this.page.goto('/login');
}
async login(email: string, password: string) {
await this.emailInput.fill(email);
await this.passwordInput.fill(password);
await this.loginButton.click();
}
}
Using Page Object in Test
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
test('valid user can login', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login('testuser@mail.com', 'Pass@123');
await expect(page).toHaveURL(/dashboard/);
});
9. What is auto-waiting in Playwright?
Playwright waits automatically before actions like click or fill. It checks if element is attached, visible, stable, and enabled. This reduces timing-related failures.
10. Why should we avoid waitForTimeout()?
Hard waits slow down tests and still do not guarantee stability. If app is slower than timeout, test fails; if faster, time is wasted. Condition-based waiting is always better.
11. What are locators in Playwright?
Locators are the recommended way to find and interact with elements. They are retry-friendly and work well with dynamic pages. They improve readability and robustness of tests.
Locators are the recommended way to find and interact with elements in Playwright. Good locator strategy makes tests more stable and less flaky.
What Is a Locator?
A locator is a smart element finder that retries automatically until the element is ready.
Unlike static selectors, Playwright locators work better with dynamic pages and reduce timing issues.
Preferred Locator Order
getByRole()getByLabel()getByPlaceholder()getByText()getByTestId()
Why This Order?
These locators are close to how users experience the app.
They are easier to read, easier to maintain, and generally more reliable than long CSS/XPath paths.
Common Locator Examples (TypeScript)
// By role (best for buttons, links, headings)
const loginBtn = page.getByRole('button', { name: 'Login' });
// By label (great for form fields)
const email = page.getByLabel('Email');
// By placeholder
const search = page.getByPlaceholder('Search products');
// By visible text
const welcomeText = page.getByText('Welcome back');
// By test id
const cartIcon = page.getByTestId('cart-icon');
Advanced Locator Usage
// Chaining locators
const cardTitle = page.locator('.product-card').first().getByRole('heading');
// Filter with text
const row = page.getByRole('row').filter({ hasText: 'Order #1234' });
// Nth element
const secondItem = page.getByRole('listitem').nth(1);
// Parent-child relation
const addBtn = page.locator('.product-card', { hasText: 'Laptop' })
.getByRole('button', { name: 'Add to Cart' });
CSS/XPath in Playwright (When Needed)
You can still use locator('css=...') or locator('//xpath'), but use them as fallback.
Prefer semantic locators first for long-term stability.
const cssElem = page.locator('css=.login-btn');
const xpathElem = page.locator('//button[text()="Login"]');
12. Which locator strategy should be preferred first?
Prefer user-facing locators like getByRole, getByLabel, getByText, and getByTestId. These are usually more stable than complex CSS/XPath chains. They also reflect real user behavior.
13. What is strict mode behavior in Playwright locators?
Playwright expects actions to target exactly one element. If locator matches multiple elements, action can fail to avoid ambiguity. This helps catch weak selectors early.
14. How do you launch browser in Playwright?
With Playwright Test Runner, browser launch is managed by config and fixtures automatically. In library mode, you can launch manually using chromium.launch(). Most teams use runner mode for clean setup.
In Playwright, browser launch can be done in two common ways: using Playwright Test Runner (recommended) or using Playwright library mode.
Method 1: Playwright Test Runner (Recommended)
Browser is launched automatically by the test runner.
You only configure browser type in playwright.config.ts and write tests using page.
Method 2: Library Mode (Manual Launch)
You launch browser yourself using chromium.launch(), create context and page manually.
Useful for custom scripts and non-test-runner workflows.
A) Launch Browser with Test Runner
1. Configure browser in playwright.config.ts:
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
use: {
browserName: 'chromium', // chromium | firefox | webkit
headless: true,
baseURL: 'https://example.com'
},
});
2. Use page fixture in test:
import { test, expect } from '@playwright/test';
test('open home page', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveTitle(/Example/);
});
B) Launch Browser Manually (Library Mode)
import { chromium } from 'playwright';
(async () => {
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com');
console.log(await page.title());
await browser.close();
})();
Headless vs Headed
- headless: true → faster, ideal for CI/CD.
- headless: false → visible browser, ideal for local debugging.
Run Commands
npx playwright test npx playwright test --headed npx playwright test --project=firefox
Use manual launch only for custom scripts or special workflows.
15. Difference between headless and headed mode?
Headless mode runs without visible browser UI and is faster for CI. Headed mode opens the UI and is useful for debugging. Teams usually run headless in pipeline and headed locally.
16. What is playwright.config.ts used for?
This file stores global test settings like base URL, retries, timeouts, browsers, reporters, and parallel workers. Centralized config keeps tests consistent across environments. It is a key framework file.
17. What are projects in Playwright config?
Projects let you run same tests under different setups, such as multiple browsers or devices. For example, Chromium + Firefox + WebKit in one command. This makes cross-browser testing simple.
18. How does parallel execution work in Playwright?
Playwright runs tests in multiple workers in parallel. This reduces total execution time significantly. Tests should be isolated to avoid data/state conflicts.
19. What are fixtures in Playwright?
Fixtures are reusable setup resources provided to tests, like page, context, and browser. You can also create custom fixtures for login, test data, etc. They reduce duplicated setup code.
20. Difference between beforeEach and beforeAll?
beforeEach runs before every test and ensures test-level freshness. beforeAll runs once and is useful for expensive shared setup. Use carefully to avoid hidden dependencies.
21. How do retries help in Playwright?
Retries rerun failed tests automatically. They help reduce random noise from temporary environment issues. But retries should not be used to hide truly flaky test design.
22. What is Playwright trace?
Trace captures detailed execution data: steps, screenshots, DOM snapshots, and network info. You can inspect it in Trace Viewer. It is one of the best tools for failure debugging.
23. What are screenshots and videos in Playwright?
Playwright can capture screenshots and record videos, especially on failure. These artifacts are very useful in CI where tests run remotely. They speed up root-cause analysis.
24. What is storageState in Playwright?
storageState stores session data like cookies and local storage. It helps reuse authenticated sessions. This avoids repeated login in every test and improves execution speed.
25. What is the best login strategy in Playwright framework?
Best approach is one-time auth setup and save session in storageState. Then reuse it for other tests. This gives faster and more stable test runs.
26. What are web-first assertions?
Web-first assertions automatically wait for expected conditions before failing. Example: expect(locator).toBeVisible(). They are better than immediate non-waiting checks.
27. Locator vs elementHandle?
Locator is recommended because it auto-retries and is resilient. ElementHandle can get stale in dynamic UI updates. Prefer locators in most automation scenarios.
28. How do you handle dropdowns in Playwright?
For native select elements, use selectOption(). For custom dropdowns, click and choose option by text/role locator. Always verify selected value after action.
Native <select> dropdown: use selectOption().
await page.locator('#country').selectOption('IN'); // by value
await page.locator('#country').selectOption({ label: 'India' }); // by label
await expect(page.locator('#country')).toHaveValue('IN');
Custom dropdown: click dropdown, then click option by text/role.
29. How to handle browser alerts/popups?
Use page.on('dialog', ...) to accept/dismiss and assert message. For new tab popups, wait using context page event. Then switch and validate new page behavior.
Use page.on('dialog') for alert/confirm/prompt.
page.on('dialog', async dialog => {
console.log(dialog.message());
await dialog.accept(); // or dialog.dismiss()
});
await page.click('button#show-alert');
For prompt: await dialog.accept('My input');
30. How to handle multiple windows/tabs?
Listen for new page event from context and store new page reference. Perform operations on that new tab explicitly. Validate URL/title to ensure proper navigation.
Wait for new page event from browser context.
const [newPage] = await Promise.all([
page.context().waitForEvent('page'),
page.click('a[target="_blank"]')
]);
await newPage.waitForLoadState();
await expect(newPage).toHaveURL(/checkout/);
Always validate URL/title before continuing actions.
31. How to upload files in Playwright?
Use setInputFiles() on file input element. It supports single or multiple files. After upload, verify success message or backend confirmation.
Use setInputFiles() on file input element.
await page.setInputFiles('input[type="file"]', 'tests/data/invoice.pdf');
await expect(page.getByText('Upload successful')).toBeVisible();
For multiple files, pass array of file paths.
32. How to work with iframes in Playwright?
Use frameLocator() to scope actions inside iframe. This keeps locator paths clear and reliable. Avoid targeting iframe elements with top-level selectors.
Use frameLocator() for safe iframe interaction.
const paymentFrame = page.frameLocator('#payment-iframe');
await paymentFrame.getByPlaceholder('Card Number').fill('4111111111111111');
await paymentFrame.getByRole('button', { name: 'Pay Now' }).click();
Avoid global selectors for iframe elements; always scope via frame.
33. How to perform hover and drag-drop actions?
Use methods like hover() and dragTo(). For complex actions, add pre/post assertions around state changes. Action call alone is not enough proof.
34. Can Playwright mock network calls?
Yes, with page.route() you can intercept and mock API responses. This helps test edge cases and unstable dependencies. It improves determinism and repeatability.
35. Can Playwright be used for API testing?
Yes, using APIRequestContext. You can run backend checks directly or combine API+UI testing in one framework. This is useful for fast setup and integration tests.
36. How should test data be managed in Playwright projects?
Store data in files, fixtures, or factories instead of hardcoding in tests. Use environment variables for sensitive values. Good data strategy makes suites reusable and maintainable.
37. How do you support multiple environments (QA/UAT)?
Use baseURL and environment-specific config through env variables. Keep secrets out of code and inside CI secret stores. This lets same suite run safely everywhere.
38. What is Page Object Model in Playwright?
POM organizes selectors and actions into reusable page classes. Tests then focus on business flow, not UI details. It improves readability and change management.
39. How do you reduce flaky tests in Playwright?
Use stable locators, web-first assertions, isolated test data, and avoid hard waits. Review failing traces to fix root cause, not symptoms. Flaky tests should be treated as defects.
40. How do you run specific tests in Playwright?
You can run by file path, test name pattern, or tags. This speeds local debugging and targeted CI runs. It is very useful for smoke/regression split.
41. Why are tags useful in Playwright automation?
Tags like @smoke, @regression help selective execution. Teams run smoke frequently and full suite on schedule. This balances speed and coverage.
42. What reporters are available in Playwright?
Common reporters include list, dot, html, json, junit. HTML is great for quick viewing and JUnit is common for CI integration. Reporting improves stakeholder visibility.
43. How do you integrate Playwright in CI/CD?
Install dependencies, execute tests headless, and publish reports/artifacts. Add pass-fail gates before deployment stages. This makes quality checks continuous and automated.
Integrating Playwright into CI/CD means running automated tests on every code change and using results as quality gates before release.
Basic CI/CD Flow
- Developer pushes code / raises PR
- Pipeline installs dependencies
- Playwright browsers are installed
- Tests run in headless mode
- HTML/JUnit reports + traces are generated
- Pipeline passes/fails based on test results
1) Required Setup
- Node.js + Playwright project
playwright.config.tswith retries/reporters- Environment variables for secrets
- Stable base URL per environment
2) CI Best Practices
- Run smoke tests on every PR
- Run full regression nightly
- Store screenshots/videos/traces as artifacts
- Fail build on critical test failures
Playwright Commands in Pipeline
npm ci npx playwright install --with-deps npx playwright test npx playwright show-report
Example: GitHub Actions Workflow
name: Playwright Tests
on:
push:
branches: [ main ]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npx playwright install --with-deps
- run: npx playwright test
- uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: playwright-report/
Useful CI/CD Tips
- Use tags (
@smoke,@regression) for selective runs. - Use retries only as support, not to hide flaky tests.
- Keep test data isolated so parallel runs don’t clash.
- Publish readable reports for Dev + QA teams.
The key is good test design, smart test splitting, and clear reporting.
44. How to handle dynamic elements in Playwright?
Prefer role/text/test-id based locators with assertions and retries. Avoid brittle index-heavy selectors. Validate state transitions before performing actions.
45. How does Playwright support mobile/responsive testing?
It provides built-in device descriptors and viewport emulation. You can run tests under mobile profiles with touch simulation. This helps validate responsive UI behavior.
46. Can Playwright automate desktop apps?
Playwright primarily targets web applications and webviews. It is not a full desktop automation tool for native Windows/macOS apps. Choose specialized tools for native desktop testing.
47. Common beginner mistakes in Playwright?
Using hard waits, weak selectors, shared state, and poor assertions are common mistakes. Another issue is skipping trace/screenshots for failures. These reduce reliability and debugging speed.
48. How do you decide timeout strategy?
Set realistic global defaults and tune only where needed. Avoid extremely high blanket values. Timeout should match real app behavior and performance SLAs.
49. Basic Playwright vs Selenium interview answer?
Playwright provides built-in auto-waiting, stronger locator APIs, modern tooling, and easier parallel setup. Selenium is mature and widely used but often needs more setup for similar convenience. Tool choice depends on team and ecosystem.
Quick Comparison Table
| Point | Playwright | Selenium |
|---|---|---|
| Architecture | Modern API, tight browser integration | WebDriver standard, browser-driver based |
| Built-in Wait Handling | Strong auto-waiting by default | Mostly explicit/implicit waits by user |
| Cross-Browser | Chromium, Firefox, WebKit | Wide browser support via WebDriver |
| Test Runner | Built-in powerful test runner | Needs external runner (JUnit/TestNG/PyTest etc.) |
| Debugging Tools | Trace viewer, video, screenshots built-in | Possible, but often with extra setup |
| Parallel Execution | Simple with built-in workers/projects | Supported, often framework/grid dependent |
| Community & Legacy Usage | Fast-growing modern adoption | Very mature and widely used historically |
When Playwright Is a Great Fit
- New automation project from scratch
- Need faster and more stable UI tests
- Need built-in CI-friendly reporting/debugging
- Team is open to modern framework patterns
When Selenium Is Still a Strong Fit
- Existing large Selenium suite already in place
- Team deeply experienced in Selenium ecosystem
- Organization standards built around WebDriver stack
- Need broad legacy integrations already available
Interview-Ready Answer
Playwright generally offers faster setup, better default stability, and stronger built-in tooling.
Selenium remains a mature, proven choice with a huge ecosystem and long enterprise history.
Tool selection should be based on project context, not hype.
If you already have a mature Selenium framework, optimize it smartly before migrating.
50. What skills are most important for Playwright QA engineers?
Strong basics in test design, selectors, async behavior, assertions, API understanding, and framework structure. Debugging with trace/reports and CI integration is also essential. Good testing thinking matters more than tool syntax alone.
You can refer below some of the short code snippets in Playwright just for the understanding purpose and to see how Playwright code appears.
1) Open a Page and Check Title
import { test, expect } from '@playwright/test';
test('page title', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle(/Example/);
});
2) Login Example
test('login flow', async ({ page }) => {
await page.goto('https://app.example.com');
await page.fill('#email', 'john@example.com');
await page.fill('#password', 'secret123');
await page.click('button:has-text("Login")');
await expect(page.locator('text=Dashboard')).toBeVisible();
});
3) Click, Search, Validate
test('search product', async ({ page }) => {
await page.goto('https://shop.example.com');
await page.fill('input[name="q"]', 'laptop');
await page.press('input[name="q"]', 'Enter');
await expect(page.locator('text=Results')).toBeVisible();
});
4) Take Screenshot
test('screenshot', async ({ page }) => {
await page.goto('https://example.com');
await page.screenshot({ path: 'home.png', fullPage: true });
});
Conclusion
The best way to crack Playwright interviews is not just memorizing definitions, but understanding why each concept is used in real projects. Focus on core areas like locators, waits, fixtures, framework design, debugging, and CI integration. If you can connect your answers to practical testing scenarios, you will stand out as a reliable QA professional who can build stable and scalable automation suites.
Discover more from Newskart
Subscribe to get the latest posts sent to your email.

[…] Playwright […]