๐ข 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:
| Feature | Playwright | Selenium |
|---|---|---|
| Auto-wait | โ Built-in | โ Manual |
| Speed | Faster | Slower |
| Multi-tab | Easy | Complex |
| Network mocking | Built-in | Limited |
| Modern support | Yes | Limited |
๐ข 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 + retrypage.$()โ 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
| Component | Description |
|---|---|
| Browser | Actual browser instance |
| Context | Isolated session |
| Page | Tab 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
| Type | Behavior |
|---|---|
| Hard | Stops execution |
| Soft | Continues 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
| Mode | Use Case |
|---|---|
| Headless | CI/CD |
| Headed | Debugging |
๐ง 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 contextcontext.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);