This guide covers the most commonly asked Playwright interview questions with answers, focusing on automation, browser handling, and test writing best practices.
If you’re new to Playwright, start with our Playwright automation tutorial to learn the basics before continuing.
Are you preparing for a QA Automation or SDET role in 2025? With Playwright becoming a popular choice for end-to-end testing, interviewers are increasingly focusing on Playwright-specific questions. In this article, we’ve compiled 40+ frequently asked Playwright interview questions and answers, ranging from beginner to advanced level. Whether you’re new to Playwright or brushing up before an interview, these questions will help you gain confidence and land your next job.
Playwright Interview Questions And Answers

1. Playwright Basic Interview Questions
This section covers essential Playwright basic interview questions that are frequently asked in automation testing interviews. Expect questions like “What is Playwright?”, “What is the architecture of Playwright?”, and “Why is Playwright often preferred over Selenium?” These questions assess your foundational knowledge of Playwright’s features, browser support, installation, and how it compares to Selenium in modern testing workflows.
Q1. What is Playwright?
Playwright is an open-source automation library developed by Microsoft. It is primarily used for end-to-end testing of web applications across multiple browsers, including Chromium (Chrome and Edge), Firefox, and WebKit (Safari). Playwright supports numerous programming languages, including JavaScript, TypeScript, Python, Java, and C#.
With Playwright, you can write reliable and fast test scripts that work consistently across different browsers and devices.
Q2. What is the architecture of Playwright?
The architecture of Playwright is based on a client-server model where your test code (client) communicates with browser engines (server) using a WebSocket or transport protocol. It supports multiple browsers and platforms through a unified API.
Key Components of Playwright Architecture:
- Test Runner / Client: Your Playwright scripts run using Node.js or the built-in Playwright Test runner.
- Playwright Core: A core library that handles automation commands and browser management across Chromium, Firefox, and WebKit.
- Browser Servers: Headless or headed browser processes launched by Playwright:
- Chromium (Chrome, Edge)
- Firefox
- WebKit (Safari)
- Communication Layer: Uses WebSocket or pipe communication to send commands from your script to the browser.
- Context & Page: Playwright creates isolated browser contexts (like incognito windows), and each context can have multiple pages (tabs).
How It Works (Simplified Flow):
- Start test using npx playwright test
- Playwright launches the target browser engine
- Commands (like click, fill, goto) are sent over the transport layer
- The browser executes actions and sends responses back to your test script
Q3. What are the key features of Playwright Automation Framework?
- Cross-browser support: Automates Chromium (Chrome, Edge), Firefox, and WebKit (Safari).
- Multiple language bindings: Write tests in JS/TS, Python, C#, or Java.
- Auto-waiting: Automatically waits for elements to be ready before performing actions.
- Headless/Headed execution: Supports running tests in both headless and visible modes.
- Network interception & mocking: Control and stub network requests.
- Mobile & device emulation: Test on mobile devices and screen sizes.
- Powerful selectors: Use CSS, text, XPath, role selectors, etc.
- Parallel execution: Fast test runs with Playwright Test runner.
Q4. What are the challenges of Playwright?
While Playwright is a powerful automation tool, it comes with a few challenges—especially when setting up or scaling in real-world projects.
Common Challenges in Playwright:
- Limited support for real CAPTCHA: Playwright can’t bypass live CAPTCHA challenges like reCAPTCHA—these must be mocked or disabled in test environments.
- Browser-level flakiness in CI/CD: Tests may pass locally but fail in CI due to environment differences, timing, or headless execution issues.
- Learning curve for advanced features: Features like context isolation, tracing, and API mocking require deeper knowledge of the framework.
- Mobile emulation, not real devices: Playwright only emulates mobile environments—it doesn’t run tests on real devices, which limits some types of testing.
- No native support for older browsers: Unlike Selenium, Playwright does not support Internet Explorer or legacy versions of browsers.
- Steep setup for multi-browser parallelism in CI: Running Chromium, Firefox, and WebKit together in CI/CD requires proper dependencies and config tuning.
Q5. How to install Playwright?
To install Playwright, you need to have Node.js installed on your machine. Playwright is available as an npm package and can be installed using a few simple commands.
Follow the steps below to install Playwright in your JavaScript project:
- Initialize a new Node.js project (if not already done):
- npm init -y
- Install Playwright using npm:
- npm install -D playwright
This command installs the Playwright library along with browser binaries for Chromium, Firefox, and WebKit.
After installation, you can verify it by writing a simple script:
const { test, expect } = require('@playwright/test');
test('Basic test - page title', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle('Example Domain');
});
Run your test using the Playwright CLI:
npx playwright test
The Playwright test runner will find your test.spec.ts file automatically and execute the test.
Q6. What browsers are supported by Playwright?
Playwright supports three major browser engines out of the box, allowing you to perform reliable cross-browser testing using a single automation framework.
Below is the list of browsers supported by Playwright:
- Chromium
- Used by Google Chrome and Microsoft Edge
- Playwright uses the open-source Chromium engine for automation
- Ideal for testing most modern web applications
- Firefox
- Based on Mozilla’s Firefox engine
- Useful for verifying compatibility with Firefox-specific features and behaviors
- WebKit
- The engine behind Safari
- Used for testing on macOS and iOS Safari
- Important for checking how your app behaves on Apple devices
This cross-browser support ensures your application behaves consistently for all users, regardless of the browser they use.
Headless and Headed Mode
Playwright supports running all these browsers in both:
- Headless mode (without UI, for faster CI execution)
- Headed mode (with UI, for local debugging)
Device and Platform Support
Playwright also allows:
- Mobile emulation (e.g., iPhone, Pixel)
- Touch events, geolocation, and network condition simulation
Q7. Is Playwright better than Selenium?
This question is commonly asked in automation testing interviews. The answer depends on your project requirements, but in many modern web testing scenarios, Playwright is considered better than Selenium due to its speed, reliability, and developer-friendly features.
Q8. Why is playwright often Preferred Over Selenium?
- Playwright handles dynamic content and auto-waiting better, reducing flaky tests.
- It allows testing across Chromium, Firefox, and WebKit, which includes Safari.
- Playwright provides rich APIs for network mocking, geolocation, and device emulation.
- It offers a modern testing experience with parallel execution, reporting, and TypeScript support out of the box.
Playwright is better than Selenium for most modern web applications. It offers faster execution, better support for modern JavaScript frameworks, and more powerful automation capabilities. However, Selenium is still a good choice for legacy systems and broader language compatibility.
2. Intermediate Level Playwright Interview Questions
This section includes intermediate-level Playwright interview questions that evaluate your practical knowledge and test execution skills using the Playwright automation framework. Commonly asked questions include: “What is auto-waiting in Playwright?”, “How do you take a screenshot in Playwright?”, and “How do you run tests in different browsers using Playwright?” You’ll also find Playwright interview questions like “What is a browser context in Playwright?”, “How do you handle file uploads in Playwright?”, and “What is the difference between await page.click() and await locator.click() in Playwright?”, which are frequently asked by interviewers to assess your understanding of asynchronous handling, file operations, and element interactions.
Q9. What is auto-waiting in Playwright?
In Playwright, auto-waiting refers to the built-in mechanism that automatically waits for the web elements to be in a ready and stable state before performing any action on them. This feature helps reduce flakiness in test scripts and makes your tests more reliable.
How Auto-Waiting Works:
Playwright automatically waits for the following conditions before proceeding with actions like click(), fill(), or type():
The element is:
- attached to the DOM
- visible
- enabled
- not moving or detached
For example:
await page.click(‘button#submit’);
You do not need to manually add waits like waitForSelector or setTimeout. Playwright will automatically wait for the button to become stable and clickable.
Benefits of Auto-Waiting:
- Reduces the need for manual wait statements
- Avoids flaky tests caused by slow-loading elements
- Handles animations, network delays, and JavaScript rendering automatically
- Makes test scripts cleaner and easier to maintain
Auto-waiting in Playwright is a feature that automatically waits for elements to be ready before interacting with them. This ensures your test scripts are stable, reliable, and free from common timing issues.
Q10. How do you take a screenshot in Playwright?
You can take a screenshot in Playwright using the page.screenshot() method. It captures the current state of the page or a specific element.
Full Page Screenshot:
await page.screenshot({ path: ‘screenshot.png’, fullPage: true });
Screenshot of an Element:
const element = await page.$(‘#login’);
await element.screenshot({ path: ‘login-button.png’ });
Screenshot on Test Failure (Playwright Test):
use: { screenshot: ‘only-on-failure’ }
Use page.screenshot() to capture full-page or element-level screenshots in Playwright. It’s helpful for debugging and visual testing.
Learn more in this step-by-step guide on how to Take a Screenshot in Playwright
Q11. How do you run tests in different browsers?
Playwright supports running tests in Chromium, Firefox, and WebKit. You can configure this easily using the Playwright Test runner.
Using Playwright Test Runner
Update playwright.config.ts to include multiple projects:
import { defineConfig } from '@playwright/test';
export default defineConfig({
projects: [
{ name: 'Chromium', use: { browserName: 'chromium' } },
{ name: 'Firefox', use: { browserName: 'firefox' } },
{ name: 'WebKit', use: { browserName: 'webkit' } },
],
});
Then run:
npx playwright test
This will run all tests in each specified browser.
Run in a Specific Browser
npx playwright test –project=firefox
Q12. What is a browser context in Playwright?
A browser context in Playwright is like an incognito or private window. It allows you to create isolated browser sessions within a single browser instance.
Each context has its own cookies, local storage, and cache—perfect for testing multiple users in parallel.
Why use contexts?
- Simulate multiple users
- Speed up tests by reusing a browser instance
- Improve test isolation without launching multiple browsers
Q13. How do you handle file uploads in Playwright?
In Playwright, file uploads are handled using the setInputFiles() method. This allows you to upload one or more files to an element.
Example:
await page.setInputFiles(‘input[type=”file”]’, ‘path/to/file.pdf’);
You can also upload multiple files:
await page.setInputFiles(‘input[type=”file”]’, [
‘path/to/file1.png’,
‘path/to/file2.png’
]);
To upload files in Playwright, use setInputFiles() and pass the file path(s) to the file input element. It’s simple and works for both single and multiple file uploads.
Read the complete guide here: Upload Files in Playwright
Q14. How do you handle asynchronous operations like waiting for elements in Playwright?
Playwright has built-in auto-waiting, which means it automatically waits for elements to be ready before interacting with them. However, you can still use manual waiting when needed—especially for dynamic content.
Example using waitForSelector():
await page.waitForSelector(‘#user-info’, { state: ‘visible’ });
await page.click(‘#user-info’);
Example using expect() (preferred):
await expect(page.locator(‘#user-info’)).toBeVisible();
Playwright’s expect() assertion includes retries and ensures the element meets the condition before proceeding.
Q15. What is the difference between await page.click() and await locator.click() in Playwright?
Both methods perform a click, but locator.click()
is more reliable because it includes automatic retries and checks for visibility, stability, and readiness.
Example with page.click():
await page.click(‘#submit-button’); // may fail if element isn’t ready
Example with locator.click() (recommended):
await page.locator(‘#submit-button’).click(); // smart auto-wait built-in
Why prefer locator.click()?
- Waits for the element to appear and be interactable
- Retries automatically if the element is temporarily unavailable
- Reduces test flakiness in async or dynamic UI scenarios
Q16. How do you generate test reports using Playwright Test?
Playwright Test comes with built-in reporter support to generate different types of test result outputs like HTML, JSON, JUnit, and more.
Example: Configure reporter in playwright.config.ts
import { defineConfig } from ‘@playwright/test’;
export default defineConfig({
reporter: [[‘html’, { open: ‘never’ }]], // Generates HTML report without auto-opening
});
You can run your tests as usual:
npx playwright test
Then open the report with:
npx playwright show-report
Q17. How do you view failed test traces in Playwright?
Playwright provides trace viewer support to help debug failed tests by capturing screenshots, DOM snapshots, and network logs.
Step 1: Enable tracing in playwright.config.ts
use: {
trace: ‘on-first-retry’, // or ‘retain-on-failure’
}
Step 2: After a test fails, run:
npx playwright show-trace trace.zip
This opens an interactive viewer to step through each test action visually.
Q18. How do you generate custom reports in Playwright?
Playwright allows you to write your own custom reporter by extending its Reporter API. This is useful when you need reporting formats tailored to your workflow.
Steps to create a custom reporter:
Create a custom reporter file (e.g., my-reporter.ts):
import type { Reporter, TestCase, TestResult } from ‘@playwright/test’;
class MyReporter implements Reporter {
onTestEnd(test: TestCase, result: TestResult) {
console.log(Test finished: ${test.title} — ${result.status}
);
}
}
export default MyReporter;
Add it to your playwright.config.ts:
import MyReporter from ‘./my-reporter’;
export default {
reporter: [[MyReporter]],
};
Mastering these intermediate Playwright interview questions is crucial for automation testers aiming to move beyond basic concepts. Topics like test reporting, viewing trace logs, and generating custom reports in Playwright are especially valuable for candidates preparing for real-world testing challenges. Make sure you’re confident with these Playwright interview questions to stand out in your next QA or SDET interview.
3. Advanced Playwright Concepts Interview Questions
This section dives into advanced Playwright interview questions designed to test your expertise in handling complex automation scenarios. Interviewers often ask questions like “How to intercept network requests in Playwright?”, “How to handle authentication in Playwright?”, and “How do you work with iframes in Playwright?” You may also encounter advanced Playwright interview questions such as “What is the use of expect() in the Playwright test runner?” and “How to execute tests in parallel in Playwright?”, which assess your ability to build scalable, robust test suites using the Playwright automation framework.
Q19. How to intercept network requests in Playwright?
Playwright allows you to intercept and modify network requests using the page.route() method. This is useful for testing with mock data, blocking resources, or logging requests.
Example:
await page.route(‘**/api/data’, route => {
console.log(‘Request URL:’, route.request().url());
route.continue(); // or route.abort() / route.fulfill()
});
You must register the route before navigating to the page.
To Mock a Response:
await page.route(‘**/api/data’, route => {
route.fulfill({
status: 200,
contentType: ‘application/json’,
body: JSON.stringify({ message: ‘Mocked response’ }),
});
});
Use page.route() to intercept, block, modify, or mock network requests in Playwright. This helps in testing edge cases and working without real APIs.
Q20. How to handle authentication in Playwright?
Playwright provides multiple ways to handle authentication, including basic auth, login sessions, and form-based logins.
Basic Authentication
Use httpCredentials when creating a new browser context:
const context = await browser.newContext({
httpCredentials: {
username: ‘user’,
password: ‘pass’
}
});
Session-Based Authentication
Login once, save storage state, and reuse it in later tests:
await page.goto(‘https://example.com/login’);
await page.fill(‘#username’, ‘user’);
await page.fill(‘#password’, ‘pass’);
await page.click(‘button[type=”submit”]’);
await context.storageState({ path: ‘state.json’ });
Then load it in tests:
const context = await browser.newContext({ storageState: ‘state.json’ });
Playwright supports basic auth and session reuse for handling authentication. You can use httpCredentials or save and load session state for login automation.
Q21. What is the use of expect() in the Playwright test runner?
In Playwright Test, the expect() function is used for assertions. It verifies that the actual result matches the expected result in your test.
Assertions help determine if a test passed or failed based on conditions.
Common Assertions:
- expect(locator).toHaveText(‘value’)
- expect(page).toHaveURL(‘https://…’)
- expect(element).toBeVisible()
Q22. How to execute tests in parallel in Playwright?
Playwright Test runs tests in parallel by default to speed up execution. Each test file runs in a separate worker process.
Parallel Test Files
No extra setup is needed. Just create multiple .spec.ts files and run:
npx playwright test
Playwright will automatically run them in parallel.
Parallel Within a File
Use test.describe.parallel() to run tests in parallel inside the same file:
import { test, expect } from ‘@playwright/test’;
test.describe.parallel(‘Login Tests’, () => {
test(‘Login as user A’, async ({ page }) => { /…/ });
test(‘Login as user B’, async ({ page }) => { /…/ });
});
Control Parallelism
You can limit workers in playwright.config.ts:
export default {
workers: 4, // number of parallel workers
};
Q23. How do you handle iframes in Playwright?
To interact with elements inside an <iframe>, Playwright provides the frame() or frameLocator() methods. These allow you to access and automate content within embedded frames.
Using frame() (based on name or URL):
const frame = page.frame({ name: ‘my-frame’ });
await frame.click(‘#button’);
Using frameLocator() (recommended in Playwright Test):
await page.frameLocator(‘#my-frame’).locator(‘button’).click();
Use frame() or frameLocator() to access and interact with elements inside iframes in Playwright. This helps in testing embedded content or third-party widgets.
These advanced Playwright interview questions challenge your problem-solving skills and real-world testing experience. Whether it’s handling network traffic, managing authentication flows, or executing parallel tests, these questions will prepare you for senior QA and automation roles. Make sure you understand each Playwright interview question in depth to showcase your technical strength during interviews.
4. Playwright vs Selenium
Feature | Playwright | Selenium |
Built-in test runner | ✅ Yes – Comes with Playwright Test | ❌ No built-in test runner |
Auto-waiting | ✅ Yes (built-in) | ❌ No (manual waits needed) |
Cross-browser support | ✅ Yes – Chromium, Firefox, WebKit | ✅ Yes – Chrome, Firefox, Safari, Edge |
Language Support | JS, TS, Python, Java, C# | Many languages supported |
Mobile emulation | ✅ Yes | ❌ Limited Basic support |
Network Interception | ✅ Built-in and powerful | Limited support |
Speed | ⚡ Faster due to single WebSocket connection | 🐢 Slower because it uses WebDriver protocol |
Headless Mode | ✅ Built-in support | ✅ Supported with setup |
Modern Web Support | ✅ Better for SPAs (React, Angular, etc.) | ❌ May require more synchronization |
5 Real-Time Scenario-Based Interview Questions
In this section, explore real-time Playwright interview questions that test how you apply Playwright in real project scenarios. Common questions include: “How would you test a drag-and-drop feature in Playwright?”, “How do you handle dynamic selectors?”, and “What if Playwright fails in CI but passes locally?”
Q24. How would you test a drag-and-drop feature in Playwright?
To test drag-and-drop in Playwright, you can use the dragTo() method available on element locators. It simulates dragging one element to another, just like a real user would.
Example:
const source = page.locator(‘#drag-source’);
const target = page.locator(‘#drop-target’);
await source.dragTo(target);
This command performs the full drag-and-drop action from the source element to the target.
Q25. How to test for broken images on a page?
To check for broken images in Playwright, you can loop through all elements and verify their HTTP response status using page.waitForResponse() or check if the image has a natural width.
Method 1: Check natural width (Quick check)
const images = await page.$$(‘img’);
for (const img of images) {
const isBroken = await img.evaluate(img => img.naturalWidth === 0);
if (isBroken) {
console.log(‘Broken image found’);
}
}
Method 2: Check image response status
page.on(‘response’, async (response) => {
const url = response.url();
if (url.endsWith(‘.jpg’) || url.endsWith(‘.png’)) {
if (!response.ok()) {
console.log(‘Broken image:’, url);
}
}
});
Q26. What would you do if Playwright fails in CI but passes locally?
If a Playwright test fails in CI but passes locally, it usually indicates an issue with timing, environment differences, or missing dependencies. Here’s how to troubleshoot:
1. Steps to Investigate:
Run tests with:
DEBUG=pw:api npx playwright test –trace on
Or use PWDEBUG=1 to see more info.
2. Check for missing environment variables or setup steps
Ensure your CI environment installs browsers:
npx playwright install –with-deps
3. Verify screen size and headless mode
CI often uses headless mode and smaller viewports. Set consistent viewport and mode in playwright.config.ts.
4. Use retries and traces
Enable retries to detect flaky tests:
retries: 1
Also, use trace viewer to debug:
npx playwright show-trace trace.zip
5. Add necessary wait or assertions
If the failure is due to timing, use proper assertions like await expect() or check for auto-wait conditions.
Q27. How do you deal with dynamic selectors in Playwright?
Dynamic selectors are elements whose attributes (like id or class) change frequently. In Playwright, you can handle them using more stable and flexible selector strategies.
Recommended Approaches:
1. Use text or role selectors
await page.getByText(‘Submit’).click();
await page.getByRole(‘button’, { name: ‘Login’ }).click();
2. Use data-testid attributes (best practice)
await page.locator(‘[data-testid=”user-name”]’).fill(‘john’);
3. Use partial matches or CSS contains
await page.locator(‘[class*=”btn-primary”]’).click();
4. Combine multiple attributes
await page.locator(‘button[type=”submit”][name=”continue”]’).click();
Q28. How do you handle multi-tab testing in Playwright?
In Playwright, you can handle multi-tab testing by creating a new page (tab) from the same browser context and switching between pages as needed.
const context = await browser.newContext();
const page1 = await context.newPage(); // first tab
await page1.goto(‘https://example.com’);
const page2Promise = context.waitForEvent(‘page’);
await page1.click(‘a[target=”_blank”]’); // opens new tab
const page2 = await page2Promise;
await page2.waitForLoadState();
console.log(await page2.title());
These scenario-based Playwright interview questions help interviewers understand your hands-on experience and debugging skills. Prepare for challenges like broken image detection, multi-tab handling, and unstable selectors to confidently handle real-world test cases.
6. Intermediate to Advanced Playwright Interview Questions
This section covers intermediate to advanced Playwright interview questions that test both your coding depth and practical automation knowledge. Frequently asked questions include: “How to handle alerts, confirms, and prompts in Playwright?”, “Can Playwright test APIs?”, and “How do you set the viewport size in Playwright?”
Q29. How to handle alerts, confirms, and prompts in Playwright?
In Playwright, you can handle JavaScript dialogs like alerts, confirms, and prompts using the page.on(‘dialog’) event.
Example:
page.on(‘dialog’, async dialog => {
console.log(dialog.message());
await dialog.accept(); // or dialog.dismiss();
});
await page.click(‘#show-alert’); // triggers alert
You can also send input to prompts:
page.on(‘dialog’, async dialog => {
await dialog.accept(‘Playwright’);
});
Q30. Can Playwright test APIs?
Yes, Playwright can test APIs using the built-in APIRequestContext feature. It allows you to send HTTP requests directly—great for backend validation or setup tasks in end-to-end tests.
Example:
const request = await playwright.request.newContext();
const response = await request.get(‘https://api.example.com/users’);
expect(response.status()).toBe(200);
You can also use post, put, delete, and patch methods to test different API operations.
Q31. How do you record/playback Playwright scripts?
Playwright provides a built-in code generator to record user actions and generate test scripts automatically. This is useful for quickly building test cases.
To Record a Script:
Use the Playwright codegen command:
npx playwright codegen https://example.com
This will:
- Launch a browser
- Record your interactions
- Generate code in JavaScript, TypeScript, Python, etc.
To Playback (Run) the Script:
Save the generated code to a file, e.g., test.spec.ts, then run:
npx playwright test
Q32. How do you set the viewport size in Playwright?
In Playwright, you can set the viewport size using the viewport option when creating a browser context.
Example:
const context = await browser.newContext({
viewport: { width: 1280, height: 720 }
});
const page = await context.newPage();
You can also set it globally in playwright.config.ts:
use: {
viewport: { width: 1440, height: 900 },
}
Q33. How to run Playwright tests in CI/CD (GitHub Actions)?
Use:
- name: Install Playwright Browsers
run: npx playwright install --with-deps
These Playwright interview questions assess your ability to manage browser dialogs, work with APIs, automate workflows, and integrate Playwright in CI/CD tools like GitHub Actions. Review them thoroughly to show strong command over real-world Playwright automation practices.
7. Test Configuration Playwright Interview Questions
This section focuses on test configuration Playwright interview questions that assess how well you manage and fine-tune your test setup. Commonly asked questions include: “How to configure Playwright test retries?”, “How to use environment-specific config in Playwright?”, and “What is storageState used for in Playwright?” These Playwright interview questions are key to mastering test reliability and flexibility.
Q34. How to configure Playwright test retries?
Playwright allows you to retry failed tests automatically by setting the retries option in the configuration file.
Example (playwright.config.ts):
import { defineConfig } from ‘@playwright/test’;
export default defineConfig({
retries: 2, // Retry failed tests up to 2 times
});
You can also set retries for specific tests
test(‘Flaky test’, async ({ page }) => {
// test code
}).retry(1);
Q35. How to use environment-specific config in Playwright?
To manage different environments (like dev, staging, prod), you can use custom environment variables or separate config files in Playwright.
Method 1: Use environment variables in playwright.config.ts
const baseURL = process.env.BASE_URL || ‘https://dev.example.com’;
export default {
use: {
baseURL,
},
};
Run with:
BASE_URL=https://staging.example.com npx playwright test
Method 2: Create multiple config files
Example: playwright.staging.config.ts, playwright.prod.config.ts
export default {
use: {
baseURL: ‘https://staging.example.com’,
},
};
Run with:
npx playwright test –config=playwright.staging.config.ts
Q36. What is storageState used for in Playwright?
In Playwright, storageState is used to save and restore the browser’s authentication state, such as cookies and localStorage. It helps you skip repetitive login steps in your tests.
How to use storageState:
- Save login session:
- await context.storageState({ path: ‘state.json’ });
- Reuse session in tests:
- const context = await browser.newContext({ storageState: ‘state.json’ });
Common Use Case:
- Login once
- Save the session
- Reuse it across multiple test files without logging in again
Q37. Can you mock geolocation in Playwright?
Yes, Playwright allows you to mock geolocation by setting coordinates in the browser context. This is useful for testing location-based features like maps or local services.
Example:
const context = await browser.newContext({
geolocation: { latitude: 37.7749, longitude: -122.4194 }, // San Francisco
permissions: [‘geolocation’],
});
const page = await context.newPage();
await page.goto(‘https://your-app.com’);
Q38. How do you assert element attributes in Playwright?
In Playwright, you can assert an element’s attribute using the toHaveAttribute() assertion provided by the test runner.
Example:
await expect(page.locator(‘input#email’)).toHaveAttribute(‘placeholder’, ‘Enter your email’);
You can also retrieve and assert manually:
const value = await page.getAttribute(‘input#email’, ‘placeholder’);
expect(value).toBe(‘Enter your email’);
Understanding these Playwright interview questions on configuration is essential for building stable and scalable test frameworks. Be ready to explain how to mock geolocation, assert element attributes, and manage different environments effectively in Playwright.
8. Real-World Debugging & Scripting Interview Questions
This section highlights real-world Playwright interview questions focused on debugging and scripting techniques. Common questions include: “How to debug tests in Playwright?”, “How to capture video of a test run?”, and “What is the role of test.describe() and test.beforeEach() in Playwright?” These questions test your ability to write maintainable and traceable automation scripts.
Q39. How to debug tests in Playwright?
Playwright provides multiple ways to debug your tests, including running in headed mode, using debugger tools, and capturing trace files.
Run in Debug Mode
Use the –debug flag to launch tests with an interactive UI and step-by-step execution:
npx playwright test –debug
This pauses on breakpoints and lets you explore actions.
Use PWDEBUG=1 for UI mode
PWDEBUG=1 npx playwright test
This opens a browser window and pauses at each step, making it easier to inspect what’s happening.
Add debugger in your test code
test(‘debug this test’, async ({ page }) => {
await page.goto(‘https://example.com’);
debugger; // execution will pause here
});
Run it with Node.js debug tools or inside VS Code.
Enable Trace Viewer
Collect trace files by updating playwright.config.ts:
use: {
trace: ‘on’, // or ‘on-first-retry’
}
Then view trace:
npx playwright show-trace trace.zip
Q41. How to capture video of a test run?
Playwright supports automatic video recording of test runs, which is helpful for debugging or sharing test failures visually.
Step 1: Enable video recording in playwright.config.ts
import { defineConfig } from ‘@playwright/test’;
export default defineConfig({
use: {
video: ‘on’, // Options: ‘on’, ‘off’, ‘retain-on-failure’, ‘on-first-retry’
},
});
Step 2: Run your tests
npx playwright test
After the run, videos will be saved under the test-results/ directory for each test.
Step 3: View the recorded video
Navigate to the test output folder and open the .webm video file to watch the test in action.
Q41. What is the role of test.describe() and test.beforeEach()?
Playwright uses test.describe() and test.beforeEach() to organize and manage test suites. These help group related tests and run shared setup code before each test.
test.describe() – Group Related Tests
Use it to logically organize tests in a block:
import { test, expect } from ‘@playwright/test’;
test.describe(‘Login Tests’, () => {
test(‘should show login form’, async ({ page }) => {
await page.goto(‘/login’);
await expect(page.locator(‘form’)).toBeVisible();
});
test(‘should login successfully’, async ({ page }) => {
// login steps
});
});
test.beforeEach() – Reuse Setup Code
This runs before each test inside the describe block:
test.describe(‘Dashboard Tests’, () => {
test.beforeEach(async ({ page }) => {
await page.goto(‘/dashboard’);
// Perform login or setup
});
test(‘should display user data’, async ({ page }) => {
await expect(page.locator(‘.user-profile’)).toBeVisible();
});
});
Q42. Can Playwright test multiple tabs or windows?
Yes, Playwright fully supports testing multiple tabs and browser windows using the same browser context. This is useful for scenarios like social logins, external redirects, or multi-page workflows.
Example: Handling a new tab
const [newPage] = await Promise.all([
context.waitForEvent(‘page’), // Waits for new tab
page.click(‘a[target=”_blank”]’), // Action that opens the tab
]);
await newPage.waitForLoadState();
expect(await newPage.title()).toContain(‘External Page’);
Example: Opening a tab manually
const page1 = await context.newPage(); // First tab
const page2 = await context.newPage(); // Second tab
await page1.goto(‘https://site.com/home’);
await page2.goto(‘https://site.com/profile’);
Q43. How to handle timeouts in Playwright?
Playwright allows you to control and handle timeouts at different levels—globally, per test, or per action. This helps manage slow-loading pages or flaky elements.
Set Global Timeout in playwright.config.ts
export default {
timeout: 30000, // Set test timeout to 30 seconds
};
Set Timeout Per Test
test(‘custom timeout’, async ({ page }) => {
test.setTimeout(20000); // 20 seconds
await page.goto(‘https://example.com’);
});
Set Timeout for Specific Actions
await page.click(‘#submit’, { timeout: 5000 }); // 5 seconds
Handle Timeout Errors Gracefully
Use try-catch for flaky actions:
try {
await page.waitForSelector(‘#modal’, { timeout: 3000 });
} catch (e) {
console.warn(‘Modal did not appear in time’);
}
These Playwright scripting and debugging interview questions are crucial for demonstrating your real-world automation experience. From managing timeouts to testing multi-tab scenarios, mastering these topics helps you troubleshoot and optimize Playwright tests effectively.
9. Scenario-Based & Troubleshooting Questions
This section features scenario-based and troubleshooting Playwright interview questions that reveal how you handle edge cases and unexpected issues. Interviewers often ask: “What if Playwright doesn’t find an element, but it’s present?”, “How do you handle CAPTCHA in Playwright?”, or “How do you emulate devices in Playwright?”
Q44. What if Playwright doesn’t find an element, but it’s present?
If Playwright can’t find an element that’s visually present, it’s usually due to timing issues, incorrect selectors, or the element not being in an interactive state yet.
How to Fix It:
- Check for auto-wait support: Use Playwright’s expect() which includes built-in waiting:
- await expect(page.locator(‘#submit’)).toBeVisible();
- Use correct and stable selectors: Avoid dynamic IDs. Prefer data-testid, role, or text selectors.
- Ensure element is attached and visible: Element may exist in the DOM but not be ready for interaction:
- await page.waitForSelector(‘#submit’, { state: ‘visible’ });
- Check for iframes or shadow DOM: The element might be inside an iframe or a shadow root.
Q45. How to handle CAPTCHA in Playwright?
Playwright does not support bypassing real CAPTCHA challenges like reCAPTCHA or hCaptcha, as they are designed to block bots and automation tools.
Recommended Approaches:
Disable CAPTCHA in test environments
Work with your dev team to disable CAPTCHA when NODE_ENV=testing.
Use test keys for reCAPTCHA
Google provides test site keys that always return valid responses.
Mock the CAPTCHA backend
Intercept network requests using page.route() and mock the CAPTCHA response:
await page.route(‘**/verify-captcha’, route => {
route.fulfill({ status: 200, body: JSON.stringify({ success: true }) });
});
Note: Playwright should not be used to solve or bypass live CAPTCHA, as this violates terms of service and ethical testing standards.
Q46. How do you emulate devices in Playwright?
Playwright allows you to emulate mobile devices using the built-in devices library, which includes presets for popular phones and tablets.
Example: Emulate iPhone 16 Pro
import { devices } from ‘@playwright/test’;
const iPhone = devices[‘iPhone 12’];
const context = await browser.newContext({
…iPhone,
});
const page = await context.newPage();
await page.goto(‘https://example.com’);
This sets the viewport, user-agent, and touch support like a real device.
Use in playwright.config.ts
use: {
…devices[‘Pixel 5’],
}
const iPhone = devices['iPhone 13'];
const context = await browser.newContext({
...iPhone
});
Q47. How to use conditional logic in tests?
In Playwright, you can use regular JavaScript/TypeScript if statements and conditions inside your test code to handle dynamic content or flows.
Example: Conditional click if element exists
const button = page.locator(‘#optional-button’);
if (await button.isVisible()) {
await button.click();
}
Example: Vary action based on environment
if (process.env.ENV === ‘staging’) {
await page.goto(‘https://staging.example.com’);
} else {
await page.goto(‘https://prod.example.com’);
}
Q48. What makes Playwright suitable for modern web testing?
- Handles SPAs well
- Rich support for selectors
- Works with real browser engines
- Parallel testing built-in
These Playwright interview questions test your critical thinking and adaptability in real-world automation problems. Be prepared to explain how to apply conditional logic in tests and manage unpredictable scenarios using Playwright’s advanced capabilities.
Q49: A test is failing intermittently. How do you make it more stable?
Intermittent or flaky tests in Playwright usually result from timing issues, unstable selectors, or non-deterministic UI behavior. Here’s how to stabilize them:
Tips to fix flaky Playwright tests:
Use locator.click() instead of page.click()
Locators come with auto-waiting and are more reliable for dynamic elements.
Add visual checks before interacting:
await expect(page.locator(‘#submit’)).toBeVisible();
await expect(page.locator(‘#submit’)).toBeEnabled();
Increase timeout if the element takes time to appear:
await page.locator(‘#submit’).click({ timeout: 10000 });
Use retries in playwright.config.ts:
retries: 2,
Enable tracing for flaky runs:
Set trace: ‘on-first-retry’ to inspect what’s causing failures.
Q50. How would you test a login flow that includes a third-party popup (like Google OAuth)?
Third-party login flows (e.g., Google OAuth) often open in a new browser tab or popup window, which you can handle in Playwright using multi-page support.
Example: Handle OAuth popup
// Trigger the OAuth login popup
const [popup] = await Promise.all([
context.waitForEvent(‘page’), // Wait for new tab
page.click(‘button.login-with-google’), // Click login button
]);
await popup.waitForLoadState();
await popup.fill(‘input[type=”email”]’, ‘your-test-email@example.com’);
// Complete OAuth flow…
await popup.click(‘button:has-text(“Next”)’);
// Wait for navigation back to the app
await page.waitForURL(‘**/dashboard’);
Q51. A button is visible but not clickable. What steps would you take?
If a button is visible but not clickable, it’s often due to overlays, animations, loaders, or the element being off-screen.
Troubleshooting Steps:
Check if the button is enabled:
await expect(page.locator(‘#submit’)).toBeEnabled();
Scroll it into view manually:
await page.locator(‘#submit’).scrollIntoViewIfNeeded();
Add a delay for animations or loaders (not recommended unless necessary):
await page.waitForTimeout(1000);
Take a screenshot to inspect layout issues:
await page.screenshot({ path: ‘debug-button.png’ });
Use Playwright’s trace viewer to visually debug clickability issues.
Final Words:
Playwright is a powerful framework for modern web automation and is rapidly gaining popularity. These 50+ Playwright interview questions and answers cover a wide range of real-world scenarios to help you succeed in your upcoming interviews. For more in-depth tutorials, check out our complete Playwright Automation tutorial series.
Hi, I’m Aravind, a seasoned Automation Test Engineer with 17+ years of industry experience. I specialize in tools like Selenium, JMeter, Appium, and Excel automation. Through this blog, I share practical tutorials, tips, and real-world insights to help testers and developers sharpen their automation skills.