Top 50+ Playwright Interview Questions with Answers 2026

Last updated on April 15th, 2026 at 05:14 am

Playwright interview questions are commonly asked questions that test your knowledge of automation basics, locator strategies, waits, browser handling, framework design, and real-world testing scenarios using Playwright.

If you are preparing for Playwright interview questions and are unsure what to expect, this guide will help you. Many candidates struggle to identify the right topics or fail to explain concepts clearly during interviews. This article is designed for beginners, experienced automation testers, and developers who want to crack Playwright interviews with confidence.

In this article, you will find a carefully curated list of Playwright interview questions based on real interview patterns. The questions are divided into beginner, intermediate, and advanced levels, so you can prepare step by step. You will also learn how to answer technical questions with clarity and explain concepts using simple logic and practical examples.

If you are new to Playwright, start with our
➡️ Playwright automation tutorial
to build strong fundamentals.

If you want hands-on experience with real projects, explore the
➡️ Enterprise Playwright Automation Framework
to understand how these concepts are applied in real automation frameworks.

By the end of this guide, you will be well prepared to answer Playwright interview questions and confidently showcase your automation skills in interviews.

Show Table of Contents
Hide Table of Contents

What are the most asked Playwright interview questions?

Playwright interview questions usually focus on:

  • Browser, BrowserContext, and Page concepts
  • Locator strategies like getByRole and getByText
  • Auto-waiting and synchronization
  • API testing and network mocking
  • Framework design, parallel execution, and CI/CD

Playwright Interview Questions And Answers 2026

Playwright Interview Questions and answers

Candidates preparing for advanced roles often use cloud hosting options for Playwright tests in enterprise setups.

1. Basic Playwright Interview Questions (With Answers)

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 framework developed by Microsoft that is used for end-to-end testing of web applications. It allows testers to automate browsers like Chromium, Firefox, and WebKit using a single API.

It supports multiple programming languages such as JavaScript, TypeScript, Python, Java, and .NET, which makes it flexible for different development teams.

In addition, Playwright provides built-in features like auto-waiting, network interception, and parallel execution, which help create stable and fast automation tests.

Q2. What is the architecture of Playwright?

Playwright follows a client-server architecture where your test script (client) communicates with browser engines (server) using a WebSocket or transport protocol.

Key Components:

  • Client (Test Script): Your Playwright code written in JavaScript, TypeScript, Python, or Java
  • Playwright Core: Manages automation and browser interactions
  • Browser Engines: Chromium, Firefox, and WebKit run in separate processes
  • Communication Layer: Uses WebSocket or pipe for sending commands
  • Browser Contexts: Isolated environments for parallel and reliable test execution
  • Pages: Individual tabs within a browser context

How It Works:

  • Playwright starts the test execution
  • It launches the required browser engine
  • Commands like click or type are sent via WebSocket
  • The browser executes actions and returns results

As a result, Playwright can run tests across multiple browsers efficiently with strong isolation and reliability.

Q3. What are the key features of Playwright Automation Framework?

Playwright provides a rich set of features that make it a powerful tool for modern web automation and testing.

  • Cross-browser support: Works with Chromium, Firefox, and WebKit (Chrome, Edge, Safari)
  • Multiple language support: Supports JavaScript, TypeScript, Python, Java, and C#
  • Auto-waiting: Automatically waits for elements to be ready before performing actions
  • Headless and headed execution: Run tests in background or with a visible browser
  • Network interception and mocking: Capture, modify, or block network requests
  • Parallel execution: Run tests faster using multiple workers
  • Mobile and device emulation: Test across different screen sizes and devices
  • Powerful selectors: Supports CSS, XPath, text, and role-based locators
  • Screenshots and videos: Capture execution for debugging and reporting
  • Built-in API testing: Test backend APIs without needing external tools

Because of this, Playwright enables fast, reliable, and scalable end-to-end testing across multiple browsers and platforms.

Q4. What are the challenges of Playwright?

Playwright is a powerful automation framework, but it has a few limitations to consider.

Common Challenges:

  • Limited support for legacy browsers: Does not support Internet Explorer or older browser versions
  • CAPTCHA handling: Cannot bypass real CAPTCHA systems like reCAPTCHA, requires mocking or disabling in test environments
  • CI/CD flakiness: Tests may behave differently in CI due to environment or timing issues
  • Learning curve: Advanced features like tracing, network mocking, and browser contexts require deeper understanding
  • Mobile testing limitation: Supports device emulation but not real device execution
  • Setup complexity: Multi-browser and parallel execution in CI may need additional configuration

That’s why teams often combine Playwright with proper test design, environment control, and CI tuning to get stable results.

Q5. How do you install Playwright?

You can install Playwright using npm. Make sure Node.js is already installed on your system.

Quick Installation (Recommended)

Run the following command:

npm init playwright@latest

This command:

  • Installs Playwright
  • Downloads supported browsers (Chromium, Firefox, WebKit)
  • Sets up a sample project

Manual Installation (Alternative)

Initialize a Node.js project:

npm init -y

Install Playwright:

npm install -D playwright

Run Your First Test

npx playwright test

Playwright will automatically detect and run your test files.

You can now start writing and executing Playwright tests.

Q6. What browsers are supported by Playwright?

Playwright supports all major modern browser engines, enabling true cross-browser testing.

Supported Browsers:

  • Chromium: Used by Google Chrome and Microsoft Edge
  • Firefox: Based on Mozilla Firefox engine
  • WebKit: The engine behind Safari, used for testing on macOS and iOS

Playwright uses these browser engines directly, which ensures accurate and consistent test results across different platforms.

Q7. Is Playwright better than Selenium?

It depends on the use case, but Playwright is often preferred for modern web applications due to its speed and built-in features.

Why Playwright is Better:

  • Auto-waiting: No need for explicit waits in most cases
  • Faster execution: Optimized for modern browsers
  • Multiple tabs and contexts: Easy handling without complex setup
  • Built-in API testing: Supports backend testing along with UI
  • Modern architecture: Designed for today’s dynamic web apps

Where Selenium Still Excels:

  • Larger community and ecosystem
  • Supports more languages and tools
  • Better support for legacy browsers like Internet Explorer

If you are testing modern applications, Playwright is usually a strong choice. For legacy systems or wider ecosystem support, Selenium may still be preferred.

For a detailed comparison, you can check our Playwright vs Selenium guide.

Q8. Why is playwright often Preferred Over Selenium?

Playwright is often preferred over Selenium for modern web applications because it provides better reliability, speed, and built-in features.

Key Reasons:

  • Auto-waiting: Handles dynamic elements automatically, which reduces flaky tests
  • Cross-browser support: Works with Chromium, Firefox, and WebKit, including Safari
  • Modern web support: Handles features like Shadow DOM and dynamic content efficiently
  • Parallel execution: Runs tests faster with built-in parallelism
  • Powerful APIs: Supports network mocking, geolocation, and device emulation
  • Better debugging: Includes tracing, screenshots, and video recording

Playwright is designed for modern testing needs, which makes it easier to write stable and maintainable test scripts.

Playwright Interview Preparation Tips

Preparing for Playwright interviews requires both theoretical knowledge and practical experience. Here are some effective tips to crack automation testing interviews:

  • Understand Playwright concepts like locators, waits, and browser handling
  • Practice real-time scenarios instead of only reading theory
  • Be comfortable with Java or Python based automation
  • Prepare common interview questions and answers thoroughly

Curious about salary? Check automation tester salary in USA to know what companies are offering.

2. Intermediate 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 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

FeaturePlaywrightSelenium
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 SupportJS, TS, Python, Java, C#Many languages supported
Mobile emulation✅ Yes❌ Limited Basic support
Network Interception✅ Built-in and powerfulLimited 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.

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. Playwright Configuration 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:

  1. Save login session:
    • await context.storageState({ path: ‘state.json’ });
  2. 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 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.

Q42. 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();
});
});

Q43. 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’);

Q44. 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 Interview 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?”

Q45. 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.

Q46. 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.

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.

Q47. 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
});

Q48. 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’);
}

Q49. 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.

Q50: 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.

Q51. 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’);

Q52. 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.

Q53. How can you implement parameterized tests in Playwright?

Parameterized tests in Playwright allow you to run the same test with multiple sets of data, which is especially useful for login, form validation, or repetitive workflows. Instead of hardcoding values, you can store them in external sources like Excel, JSON, or CSV, and loop through them at runtime.

For example, many QA teams use Excel-driven tests where usernames and passwords are read dynamically. In Playwright, you can achieve this by integrating libraries like ExcelJS and creating a utility to fetch data before executing tests.

I’ve explained this in detail with a working Excel-driven framework here:

Playwright Parameterized Tests in JavaScript

Q54. What is the Page Object Model (POM) in Playwright and why should you use it?

The Page Object Model (POM) is a design pattern that helps in maintaining clean, reusable, and scalable test code. Instead of scattering locators and actions inside test files, you create separate page classes where each class represents a page in your application.

This approach makes your tests more maintainable, for example, if a locator changes, you only update it in one place. Playwright works seamlessly with POM because it supports reusable classes and async methods for actions like login, navigation, and form submission.

You can check a complete step-by-step guide with code here:

Playwright Page Object Model in JavaScript

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.

To prepare better, explore how AI-powered Playwright script generation works in real workflows.

author avatar
Aravind QA Automation Engineer & Technical Blogger
Aravind is a QA Automation Engineer and technical blogger specializing in Playwright, Selenium, and AI in software testing. He shares practical tutorials to help QA professionals improve their automation skills.

Leave a Reply

Your email address will not be published. Required fields are marked *