Playwright Advanced Interview Practice
Prepare for your next SDET or QA interview with curated questions and answers.
Answer: Playwright can be integrated into CI/CD pipelines to run automated tests on every code push, pull request, or deployment.
GitHub Actions Example
name: Playwright Tests
on:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Dependencies
run: npm install
- name: Install Playwright Browsers
run: npx playwright install --with-deps
- name: Run Tests
run: npx playwright testJenkins Integration
- Install Node.js in Jenkins machine
- Configure Jenkins pipeline
- Run:
npm install
npx playwright install
npx playwright testAzure DevOps
Use YAML pipeline:
- script: npm install
- script: npx playwright install --with-deps
- script: npx playwright testAnswer: A scalable framework should be modular, reusable, and maintainable.
Recommended Structure
project/
│
├── tests/
├── pages/
├── utils/
├── fixtures/
├── test-data/
├── api/
├── playwright.config.ts
└── package.jsonBest Practices
- Use Page Object Model (POM)
- Keep reusable utilities separate
- Store test data externally
- Use fixtures for setup/teardown
- Maintain environment configs
Example POM
export class LoginPage {
constructor(private page) {}
async login(username: string, password: string) {
await this.page.fill('#user', username);
await this.page.fill('#pass', password);
await this.page.click('#login');
}
}Answer: Playwright supports both browser automation and API testing.
Example
import { test, expect, request } from '@playwright/test';
test('API + UI Validation', async ({ page }) => {
// API Call
const apiContext = await request.newContext();
const response = await apiContext.get('https://reqres.in/api/users/2');
expect(response.status()).toBe(200);
// UI Validation
await page.goto('https://example.com');
await expect(page.locator('h1')).toContainText('Example');
});Advantages
- End-to-end validation
- Faster setup using APIs
- Backend + frontend verification
Answer: Environment variables help switch between QA, UAT, PROD, etc.
.env File
BASE_URL=https://qa.example.com
USERNAME=admin
PASSWORD=admin123Install dotenv
npm install dotenvplaywright.config.ts
import dotenv from 'dotenv';
dotenv.config();
export default defineConfig({
use: {
baseURL: process.env.BASE_URL
}
});Usage
await page.goto(process.env.BASE_URL!);Answer: Playwright supports multiple reporters.
HTML Report
reporter: [['html']]Run:
npx playwright show-reportAllure Report
Install:
npm install -D allure-playwrightConfig:
reporter: [
['line'],
['allure-playwright']
]Generate Report:
allure generate ./allure-results --clean
allure openBenefits
- Screenshots
- Videos
- Failure traces
- Execution analytics
Answer: Playwright supports parallel execution using projects and workers.
Example
projects: [
{
name: 'Chrome',
use: { browserName: 'chromium' }
},
{
name: 'Firefox',
use: { browserName: 'firefox' }
},
{
name: 'Mobile Chrome',
use: devices['Pixel 5']
}
]Run Tests
npx playwright test --workers=4Advantages
- Faster execution
- Cross-browser validation
- Device compatibility testing
Answer: Launch options help simulate real environments.
Example
use: {
launchOptions: {
headless: true,
slowMo: 100,
args: ['--disable-gpu']
}
}Network Throttling
await page.route('**/*', async route => {
await route.continue();
});Useful Options
- Headless mode
- CPU throttling
- Network simulation
- Disable cache
Answer:
1. Headed Mode
npx playwright test --headed2. Debug Mode
npx playwright test --debug3. Pause Execution
await page.pause();4. Trace Viewer
npx playwright show-trace trace.zipEnable Trace
use: {
trace: 'on-first-retry'
}Benefits
- Step-by-step execution
- DOM inspection
- Network analysis
- Screenshots and videos
Answer:
Capture Console Logs
page.on('console', msg => {
console.log(msg.text());
});Capture JavaScript Errors
page.on('pageerror', error => {
console.log('JS Error:', error.message);
});Example
test('Capture errors', async ({ page }) => {
page.on('console', msg => console.log(msg.text()));
page.on('pageerror', err =>
console.log(err.message)
);
await page.goto('https://example.com');
});Answer: BDD allows writing tests in Gherkin syntax.
Install
npm install @cucumber/cucumberFeature File
Feature: Login
Scenario: Valid Login
Given user opens login page
When user enters credentials
Then dashboard should appearStep Definition
test('Capture errors', async ({ page }) => {
page.on('console', msg => console.log(msg.text()));
page.on('pageerror', err =>
console.log(err.message)
);
await page.goto('https://example.com');
});Benefits
- Business-readable tests
- Better collaboration
- Reusable steps
Answer: Docker ensures consistent execution across environments.
Dockerfile
FROM mcr.microsoft.com/playwright:v1.52.0-jammy
WORKDIR /app
COPY . .
RUN npm install
CMD ["npx", "playwright", "test"]Build Image
docker build -t playwright-tests .Run Container
docker run playwright-testsAdvantages
- Environment consistency
- Easy CI/CD integration
- Scalable execution
Answer: Playwright supports multiple languages.
Java Example
Browser browser = playwright.chromium().launch();
Page page = browser.newPage();
page.navigate("https://example.com");Python Example
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://example.com").NET Example
await page.GotoAsync("https://example.com");Benefits
- Language flexibility
- Team compatibility
- Shared automation concepts
Answer: Mocking helps test without real backend dependency.
Example
await page.route('**/api/users', async route => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
name: 'Dhiraj',
role: 'QA'
})
});
});Benefits
- Faster tests
- Stable automation
- Offline execution
- Negative scenario testing
Answer:
Common Issues
- Hardcoded waits
- Dynamic elements
- Slow Network
- Shared test data
- Negative scenario testing
Here is the prevention technique for network flakiness:
Use Auto Waiting
await locator.click();Avoid Static Waits
❌ Bad
await page.waitForTimeout(5000);✅ Good
await expect(locator).toBeVisible();Use Stable Locators
page.getByTestId('submit-btn');Retry Failed Tests
retries: 2Isolate Tests
- Independent test data
- Fresh browser context
Answer:
1. Use Page Object Model
Separates UI actions from test logic.
2. Reusable Utilities
Create helper methods for:
- Login
- API calls
- Data generation
- Database operations
3. Proper Folder Structure
pages/
tests/
utils/
fixtures/
data/4. Centralized Configurations
baseURL
timeouts
retries
reporters5. Use Fixtures
test.beforeEach(async ({ page }) => {
await page.goto('/');
});6. CI/CD Integration
Run automated tests in pipelines.
7. Parallel Execution
Improves execution speed.
8. Tagging & Grouping
npx playwright test --grep @smoke9. Logging & Reporting
- HTML reports
- Allure reports
- Screenshots/videos
10. Code Reviews & Standards
Maintain clean, reusable, readable automation code.