Playwright Interview Questions & Answers

๐ŸŸข 1. What is Playwright?

Answer:
Playwright is an open-source automation framework developed by Microsoft for end-to-end testing of web applications.

Key Features:

  • Cross-browser support (Chromium, Firefox, WebKit)
  • Auto-waiting
  • Headless & headed execution
  • Parallel execution
  • Network interception

๐ŸŸข 2. Why Playwright over Selenium?

Answer:

FeaturePlaywrightSelenium
Auto-waitโœ… Built-inโŒ Manual
SpeedFasterSlower
Multi-tabEasyComplex
Network mockingBuilt-inLimited
Modern supportYesLimited

๐ŸŸข 3. How to install Playwright?

Answer:

npm init playwright@latest

๐ŸŸข 4. Basic Test Example

import { test, expect } from '@playwright/test';test('Google search test', async ({ page }) => {
await page.goto('https://google.com');
await page.fill('input[name="q"]', 'Playwright');
await page.press('input[name="q"]', 'Enter');
await expect(page).toHaveTitle(/Playwright/);
});

๐ŸŸก 5. What is Auto-Waiting?

Answer:
Playwright automatically waits for:

  • Elements to be visible
  • Elements to be stable
  • Network to be idle

Example:

await page.click('#submit'); // waits automatically

๐ŸŸก 6. What are Locators?

Answer:
Locators are used to find elements.

page.locator('#id');
page.locator('.class');
page.getByText('Login');
page.getByRole('button', { name: 'Submit' });

๐ŸŸก 7. Difference between locator() and page.$()

Answer:

  • locator() โ†’ Auto-wait + retry
  • page.$() โ†’ Returns immediately (not reliable)

๐ŸŸก 8. How to handle dropdowns?

await page.selectOption('#dropdown', 'value1');

๐ŸŸก 9. Handling checkboxes

await page.check('#checkbox');
await page.uncheck('#checkbox');

๐ŸŸก 10. Handling alerts

page.on('dialog', async dialog => {
await dialog.accept();
});

๐Ÿ”ต 11. How to handle multiple tabs?

const [newPage] = await Promise.all([
context.waitForEvent('page'),
page.click('#openTab')
]);await newPage.waitForLoadState();

๐Ÿ”ต 12. File upload

await page.setInputFiles('#fileInput', 'test.pdf');

๐Ÿ”ต 13. File download

const [download] = await Promise.all([
page.waitForEvent('download'),
page.click('#downloadBtn')
]);await download.saveAs('file.pdf');

๐Ÿ”ต 14. What is Page Object Model (POM)?

Answer:
Design pattern to separate UI and test logic.

Example:

export class LoginPage {
constructor(private page) {} async login(username, password) {
await this.page.fill('#user', username);
await this.page.fill('#pass', password);
await this.page.click('#login');
}
}

๐Ÿ”ต 15. API Testing in Playwright

import { request } from '@playwright/test';test('API Test', async () => {
const apiContext = await request.newContext();
const response = await apiContext.get('/api/users');
console.log(await response.json());
});

๐Ÿ”ด 16. How to handle authentication?

test.use({ storageState: 'auth.json' });

Save session:

await page.context().storageState({ path: 'auth.json' });

๐Ÿ”ด 17. Parallel Execution

npx playwright test --workers=4

๐Ÿ”ด 18. Retry Failed Tests

// playwright.config.ts
retries: 2

๐Ÿ”ด 19. How to handle dynamic elements?

await page.locator('//button[text()="Submit"]').click();

Use:

  • XPath
  • contains()
  • text-based locators

๐Ÿ”ด 20. Network Interception

await page.route('**/api/users', route => {
route.fulfill({
status: 200,
body: JSON.stringify({ name: 'Mock User' })
});
});

๐Ÿง  Advanced Scenario-Based Questions


๐Ÿ”ฅ 21. Banking App Login + OTP

Solution Approach:

  • Mock OTP API
  • Use API interception
await page.route('**/otp', route => {
route.fulfill({ body: JSON.stringify({ otp: '123456' }) });
});

๐Ÿ”ฅ 22. E-commerce Add to Cart Flow

await page.click('text=Add to Cart');
await expect(page.locator('#cart')).toContainText('1 item');

๐Ÿ”ฅ 23. Handling Flaky Tests

Best Practices:

  • Use locators instead of selectors
  • Avoid hard waits
  • Use waitForLoadState()

๐Ÿ”ฅ 24. Multi-user Session (Admin + User)

const adminContext = await browser.newContext();
const userContext = await browser.newContext();const adminPage = await adminContext.newPage();
const userPage = await userContext.newPage();

๐Ÿ”ฅ 25. CI/CD Integration

Use:

  • GitHub Actions
  • Jenkins

Example:

- name: Run Playwright Tests
run: npx playwright test

26. What is Browser Context in Playwright?

Answer:
A Browser Context is an isolated session (like an incognito window).

Why important?

  • Test isolation
  • Multi-user testing
  • No shared cookies/session
const context = await browser.newContext();
const page = await context.newPage();

๐Ÿ‘‰ Think: One browser โ†’ multiple contexts โ†’ multiple users


๐Ÿ”ด 27. Difference between Browser, Context, and Page

ComponentDescription
BrowserActual browser instance
ContextIsolated session
PageTab inside context

๐Ÿ”ด 28. How to reuse login session across tests?

Answer:
Use storage state

// Save session
await context.storageState({ path: 'auth.json' });// Reuse session
test.use({ storageState: 'auth.json' });

๐Ÿ”ด 29. How to handle iFrames?

const frame = page.frameLocator('#frameId');
await frame.locator('#input').fill('Hello');

๐Ÿ”ด 30. Shadow DOM handling

await page.locator('css=custom-element >> text=Submit').click();

๐Ÿ”ด 31. How to debug Playwright tests?

Answer:

Run in debug mode:

npx playwright test --debug

Use:

await page.pause();

๐Ÿ”ด 32. Trace Viewer in Playwright

Answer:
Playwright provides a trace viewer for debugging failures.

npx playwright show-trace trace.zip

๐Ÿ”ด 33. How to capture screenshots?

await page.screenshot({ path: 'screenshot.png' });

Full page:

await page.screenshot({ path: 'full.png', fullPage: true });

๐Ÿ”ด 34. How to record videos?

const context = await browser.newContext({
recordVideo: { dir: 'videos/' }
});

๐Ÿ”ด 35. Handling dynamic waits (best approach)

Avoid:

await page.waitForTimeout(5000); โŒ

Use:

await page.waitForSelector('#element'); โœ…

๐Ÿ”ด 36. Soft Assertions in Playwright

import { expect } from '@playwright/test';await expect.soft(page.locator('#status')).toHaveText('Success');

๐Ÿ”ด 37. Hard vs Soft Assertions

TypeBehavior
HardStops execution
SoftContinues execution

๐Ÿ”ด 38. How to run specific test file?

npx playwright test login.spec.ts

๐Ÿ”ด 39. Run tests in headed mode

npx playwright test --headed

๐Ÿ”ด 40. Environment configuration

// playwright.config.ts
use: {
baseURL: 'https://staging.example.com'
}

Usage:

await page.goto('/');

๐Ÿง  Real-Time Scenario Questions (Very Important)


๐Ÿ”ฅ 41. Scenario: Element is visible but click fails

Possible reasons:

  • Overlay present
  • Element not stable
  • Animation

Solution:

await page.locator('#btn').click({ force: true });

Better:

await expect(locator).toBeVisible();
await locator.click();

๐Ÿ”ฅ 42. Scenario: Test passes locally but fails in CI

Reasons:

  • Timing issues
  • Environment difference
  • Headless issues

Fix:

  • Use proper waits
  • Enable retries
  • Use trace viewer

๐Ÿ”ฅ 43. Scenario: Handling infinite scrolling

await page.evaluate(() => window.scrollBy(0, window.innerHeight));

Loop until element appears:

while (!(await page.locator('#item').isVisible())) {
await page.mouse.wheel(0, 1000);
}

๐Ÿ”ฅ 44. Scenario: Validate table data

const rows = page.locator('table tr');const count = await rows.count();for (let i = 0; i < count; i++) {
const text = await rows.nth(i).textContent();
console.log(text);
}

๐Ÿ”ฅ 45. Scenario: Handling date picker

await page.click('#date');
await page.click('text=25');

๐Ÿ”ฅ 46. Scenario: Handling authentication popup

await page.goto('https://user:pass@example.com');

๐Ÿ”ฅ 47. Scenario: Drag and Drop

await page.dragAndDrop('#source', '#target');

๐Ÿ”ฅ 48. Scenario: Handling file download validation

const path = await download.path();
expect(path).toContain('file');

๐Ÿ”ฅ 49. Scenario: Validate API response + UI

const response = await page.waitForResponse('**/api/data');
const data = await response.json();expect(data.name).toBe('Test');

๐Ÿ”ฅ 50. Scenario: Retry only failed tests

npx playwright test --retries=2

๐ŸŽฏ Advanced Framework Design Questions


๐Ÿ”ท 51. How do you design a scalable Playwright framework?

Answer:

Structure:

tests/
pages/
utils/
fixtures/
config/

Best practices:

  • Use POM
  • Use fixtures
  • Use environment configs
  • Separate test data

๐Ÿ”ท 52. What are fixtures in Playwright?

test('example', async ({ page }) => {
// page is a fixture
});

Custom fixture:

test.extend({
loginPage: async ({ page }, use) => {
await use(new LoginPage(page));
}
});

๐Ÿ”ท 53. Data-driven testing

const users = ['user1', 'user2'];for (const user of users) {
test(`login test ${user}`, async ({ page }) => {
console.log(user);
});
}

๐Ÿ”ท 54. Parallel vs Serial execution

test.describe.configure({ mode: 'parallel' });

Serial:

test.describe.configure({ mode: 'serial' });

๐Ÿ”ท 55. Tags in Playwright

test('smoke test @smoke', async () => {});

Run:

npx playwright test -g "@smoke"

โš ๏ธ Tricky Interview Questions


โ“ 56. Why Playwright is faster?

  • WebSocket communication
  • No Selenium WebDriver layer
  • Direct browser control

โ“ 57. Can Playwright handle multiple browsers at once?

Yes:

projects: [
{ name: 'Chromium' },
{ name: 'Firefox' },
{ name: 'WebKit' }
]

โ“ 58. What happens if locator matches multiple elements?

  • Playwright throws strict mode error

Fix:

locator.first()
locator.nth(0)

โ“ 59. Difference between waitForSelector and locator wait

  • locator โ†’ auto-wait
  • waitForSelector โ†’ manual wait

โ“ 60. How do you reduce flakiness?

โœ” Use locators
โœ” Avoid hard waits
โœ” Use retries
โœ” Mock APIs
โœ” Stable selectors

๐Ÿ”ฅ 61. Scenario: Banking App โ€“ Secure Login with Token

Problem:
Login uses JWT token instead of UI login.

Solution:

  • Call API
  • Inject token into storage
const requestContext = await request.newContext();const response = await requestContext.post('/api/login', {
data: { username: 'user', password: 'pass' }
});const body = await response.json();await context.addCookies([{
name: 'token',
value: body.token,
domain: 'example.com',
path: '/'
}]);

๐Ÿ”ฅ 62. Scenario: Bypass CAPTCHA (Important Interview Question)

Reality:
Playwright cannot solve CAPTCHA

Best Practice:

  • Disable CAPTCHA in test environment
  • Mock API

๐Ÿ”ฅ 63. Scenario: Handling WebSocket Testing

page.on('websocket', ws => {
ws.on('framereceived', frame => {
console.log(frame.payload);
});
});

๐Ÿ”ฅ 64. Scenario: Test microservices-based UI

Approach:

  • Mock dependent APIs
  • Validate UI independently
await page.route('**/orders', route => {
route.fulfill({ body: JSON.stringify({ orders: [] }) });
});

๐Ÿ”ฅ 65. Scenario: Handling flaky network

await page.route('**/*', route => {
route.continue({ timeout: 10000 });
});

๐Ÿ”ฅ 66. Scenario: Validate PDF download content

const buffer = await download.createReadStream();

Then parse using Node libraries


๐Ÿ”ฅ 67. Scenario: Multi-language testing

await page.goto('/?lang=fr');
await expect(page.locator('h1')).toHaveText('Bonjour');

๐Ÿ”ฅ 68. Scenario: Geo-location testing

const context = await browser.newContext({
geolocation: { latitude: 28.6139, longitude: 77.2090 },
permissions: ['geolocation']
});

๐Ÿ”ฅ 69. Scenario: Timezone testing

const context = await browser.newContext({
timezoneId: 'Asia/Kolkata'
});

๐Ÿ”ฅ 70. Scenario: Testing notifications

await context.grantPermissions(['notifications']);

๐Ÿ—๏ธ Framework Architecture Questions (Very Important)


๐Ÿ”ท 71. How to design enterprise-level Playwright framework?

Layers:

1. Tests
2. Page Objects
3. API Layer
4. Utilities
5. Test Data
6. Config

Key Additions:

  • Logging
  • Reporting
  • Retry strategy
  • Test tagging

๐Ÿ”ท 72. How to implement reusable utilities?

Example:

export async function login(page, user) {
await page.fill('#user', user);
}

๐Ÿ”ท 73. Centralized test data management

Use:

  • JSON files
  • Environment variables
const data = require('./testData.json');

๐Ÿ”ท 74. Logging in Playwright

Use console or integrate with tools like:

  • Winston
  • Custom logger

๐Ÿ”ท 75. Reporting tools

Playwright supports:

  • HTML report
  • Allure report
npx playwright show-report

โš™๏ธ CI/CD + DevOps Questions


๐Ÿ”ง 76. How to run Playwright in CI/CD?

Using GitHub Actions:

name: Playwright Testson: [push]jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: npm install
- run: npx playwright install
- run: npx playwright test

๐Ÿ”ง 77. How to run tests in Docker?

FROM mcr.microsoft.com/playwright:v1.40.0
WORKDIR /app
COPY . .
RUN npm install
CMD ["npx", "playwright", "test"]

๐Ÿ”ง 78. Headless vs Headed execution

ModeUse Case
HeadlessCI/CD
HeadedDebugging

๐Ÿ”ง 79. How to reduce execution time?

โœ” Parallel execution
โœ” API mocking
โœ” Reuse authentication
โœ” Run only changed tests


๐Ÿ”ง 80. Sharding tests

npx playwright test --shard=1/3

๐Ÿ” Debugging & Optimization


๐Ÿ› ๏ธ 81. How to debug failed tests in CI?

  • Use trace viewer
  • Capture video
  • Capture logs

๐Ÿ› ๏ธ 82. Memory leak issues

Cause:

  • Not closing contexts
await context.close();

๐Ÿ› ๏ธ 83. Handling slow tests

  • Remove unnecessary steps
  • Use API setup instead of UI
  • Use fixtures

๐Ÿ› ๏ธ 84. Test retries strategy

retries: process.env.CI ? 2 : 0

๐Ÿ› ๏ธ 85. Fail fast strategy

maxFailures: 5

๐Ÿ” Security Testing (Important)


๐Ÿ”’ 86. How to test authentication security?

  • Validate token expiration
  • Test invalid login

๐Ÿ”’ 87. How to test authorization?

  • Admin vs user roles
expect(await page.isVisible('#adminPanel')).toBeFalsy();

๐Ÿ”’ 88. Sensitive data handling

  • Avoid hardcoding credentials
  • Use env variables

๐Ÿ”’ 89. HTTPS validation

expect(page.url()).toContain('https');

๐Ÿ”’ 90. Cookie testing

const cookies = await context.cookies();

๐ŸŽฏ Expert-Level Tricky Questions


โ“ 91. Difference between browser.newPage() and context.newPage()

  • browser.newPage() โ†’ new default context
  • context.newPage() โ†’ controlled session

โ“ 92. Why avoid waitForTimeout()?

  • Causes flaky tests
  • Slows execution

โ“ 93. How Playwright handles race conditions?

  • Auto-waiting
  • Event-based execution

โ“ 94. Can Playwright test backend?

Yes:

  • API testing
  • Contract testing

โ“ 95. How to test file upload without UI?

await request.post('/upload', {
multipart: { file: fs.createReadStream('file.txt') }
});

โ“ 96. What is test isolation?

Each test runs independently with:

  • New context
  • Clean state

โ“ 97. How to handle feature flags?

await page.goto('/?feature=true');

โ“ 98. How to test performance?

Basic:

const start = Date.now();
await page.goto('/');
console.log(Date.now() - start);

โ“ 99. Can Playwright run without UI?

Yes โ†’ headless mode


โ“ 100. When NOT to use Playwright?

  • Desktop app testing
  • Heavy performance testing (use JMeter)

Real-World Enterprise Scenarios in Playwright


๐Ÿฆ 1. Banking App โ€“ End-to-End Payment Flow

๐ŸŽฏ Problem

User logs in โ†’ adds beneficiary โ†’ transfers money โ†’ verifies transaction.

โœ… Approach

  • Reuse login session
  • Mock OTP service
  • Validate UI + API

๐Ÿ’ป Example

test('Fund transfer flow', async ({ page }) => {
await page.goto('/dashboard'); await page.click('text=Transfer');
await page.fill('#account', '123456');
await page.fill('#amount', '5000');
await page.click('#submit'); await expect(page.locator('#status')).toHaveText('Success');
});

๐Ÿง  Best Practices

  • Avoid real payment โ†’ mock API
  • Validate transaction via backend API
  • Use test accounts

๐Ÿ›’ 2. E-Commerce โ€“ Add to Cart + Checkout

๐ŸŽฏ Problem

User adds product โ†’ applies coupon โ†’ completes checkout.

โœ… Approach

  • Use stable locators
  • Mock payment gateway
  • Validate price calculation

๐Ÿ’ป Example

await page.click('text=Add to Cart');
await page.fill('#coupon', 'DISCOUNT10');
await page.click('#apply');await expect(page.locator('#total')).toContainText('900');

๐Ÿง  Best Practices

  • Mock payment APIs
  • Validate cart via API
  • Use data-driven tests

๐Ÿ‘ฅ 3. Multi-User Role Testing (Admin vs User)

๐ŸŽฏ Problem

Admin creates data โ†’ user verifies it.

โœ… Approach

  • Use multiple browser contexts

๐Ÿ’ป Example

const adminContext = await browser.newContext();
const userContext = await browser.newContext();const adminPage = await adminContext.newPage();
const userPage = await userContext.newPage();await adminPage.goto('/admin');
await adminPage.click('#createUser');await userPage.goto('/dashboard');

๐Ÿง  Best Practices

  • Keep sessions isolated
  • Avoid shared cookies

๐Ÿ” 4. Authentication Without UI (Token-Based Login)

๐ŸŽฏ Problem

Login via API instead of UI (faster + stable)

โœ… Approach

  • Call login API
  • Inject token

๐Ÿ’ป Example

const response = await request.post('/api/login', {
data: { username: 'user', password: 'pass' }
});const { token } = await response.json();await context.addCookies([{ name: 'token', value: token }]);

๐Ÿง  Best Practices

  • Avoid UI login in every test
  • Store auth state

๐ŸŒ 5. Microservices UI โ€“ API Mocking

๐ŸŽฏ Problem

Frontend depends on unstable backend services

โœ… Approach

  • Mock APIs

๐Ÿ’ป Example

await page.route('**/orders', route => {
route.fulfill({
body: JSON.stringify({ orders: [] })
});
});

๐Ÿง  Best Practices

  • Test UI independently
  • Simulate edge cases

๐Ÿ“Š 6. Data Validation Between UI and API

๐ŸŽฏ Problem

Ensure UI data matches backend response

๐Ÿ’ป Example

const response = await page.waitForResponse('**/api/user');
const apiData = await response.json();const uiText = await page.locator('#username').textContent();expect(uiText).toBe(apiData.name);

๐Ÿง  Best Practices

  • Validate critical fields
  • Avoid over-validating

๐Ÿ“ฑ 7. Mobile Device Testing

๐ŸŽฏ Problem

Test responsive UI

๐Ÿ’ป Example

import { devices } from '@playwright/test';test.use(devices['iPhone 13']);

๐Ÿง  Best Practices

  • Test key flows only
  • Avoid duplicating all tests

๐Ÿ“ฆ 8. File Upload & Download Validation

๐ŸŽฏ Problem

Upload invoice โ†’ download receipt โ†’ verify

๐Ÿ’ป Example

await page.setInputFiles('#upload', 'invoice.pdf');const [download] = await Promise.all([
page.waitForEvent('download'),
page.click('#download')
]);

๐Ÿง  Best Practices

  • Validate file name
  • Validate file content (if critical)

๐Ÿ” 9. Handling Retry & Flaky Tests

๐ŸŽฏ Problem

Tests fail intermittently in CI

โœ… Fix

retries: 2

๐Ÿง  Best Practices

  • Fix root cause (donโ€™t rely only on retry)
  • Use trace viewer

๐Ÿงพ 10. Infinite Scroll / Lazy Loading

๐ŸŽฏ Problem

Data loads on scroll

๐Ÿ’ป Example

while (!(await page.locator('#item').isVisible())) {
await page.mouse.wheel(0, 1000);
}

๐Ÿง  Best Practices

  • Add exit condition
  • Avoid infinite loops

๐Ÿงช 11. Feature Flag Testing

๐ŸŽฏ Problem

Feature enabled only for some users

๐Ÿ’ป Example

await page.goto('/?feature=true');

๐Ÿง  Best Practices

  • Test both ON and OFF states

๐ŸŒ 12. Localization Testing

๐ŸŽฏ Problem

App supports multiple languages

๐Ÿ’ป Example

await page.goto('/?lang=hi');
await expect(page.locator('h1')).toHaveText('เคจเคฎเคธเฅเคคเฅ‡');

๐Ÿง  Best Practices

  • Validate key UI texts
  • Avoid full UI comparison

๐Ÿ“ 13. Geo-Location Testing

๐ŸŽฏ Problem

Content varies by location

๐Ÿ’ป Example

await context.setGeolocation({ latitude: 28.61, longitude: 77.20 });

๐Ÿ”„ 14. Background Job Validation

๐ŸŽฏ Problem

Async job updates UI later

๐Ÿ’ป Example

await expect(page.locator('#status')).toHaveText('Completed', { timeout: 10000 });

โš™๏ธ 15. CI/CD Pipeline Execution

๐ŸŽฏ Problem

Run tests on every deployment

๐Ÿ’ป Example

Using Jenkins or GitHub Actions

npx playwright test

๐Ÿ”ฅ 16. Handling CAPTCHA in Enterprise Apps

โ— Reality

Automation tools should not bypass CAPTCHA

โœ… Approach

  • Disable in test env
  • Use mock/stub

๐Ÿง  17. High Data Volume Testing (Tables)

๐ŸŽฏ Problem

Validate large tables

๐Ÿ’ป Example

const rows = await page.locator('table tr');
expect(await rows.count()).toBeGreaterThan(0);

๐Ÿ” 18. Role-Based Access Testing

๐ŸŽฏ Problem

User should not access admin pages

๐Ÿ’ป Example

await page.goto('/admin');
await expect(page).toHaveURL('/unauthorized');

โšก 19. Performance Check (Basic)

๐Ÿ’ป Example

const start = Date.now();
await page.goto('/');
console.log(Date.now() - start);

Leave a Comment