๐ŸŽญ Next Gen QA

Playwright
100+ Interview Questions

Basic to Advanced โ€” Complete Interview Preparation Guide

๐ŸŽฏ 100+ Questions
๐Ÿ“‚ 8 Categories
๐Ÿ’ป Code Every Answer
๐Ÿ‘จโ€๐Ÿ’ป Khan Sir โ€” 8700350994
100+
Questions
8
Categories
100%
Code Examples
Free
Resource
๐Ÿ”
๐Ÿ”นBasic Concepts18 Qs
01
What is Playwright? Who made it?
โ–ผ
Playwright is a modern, open-source browser automation framework developed by Microsoft. It allows you to write end-to-end tests and automate web browsers. It supports Chromium, Firefox, and WebKit with a single API and is available in JavaScript/TypeScript, Python, Java, and C#.
02
What are the key differences between Playwright and Selenium?
โ–ผ
FeaturePlaywrightSelenium
Auto-waitโœ… Built-inโŒ Manual waits
Shadow DOMโœ… Auto-pierceโŒ Complex workarounds
Network Mockโœ… Built-inโŒ Third-party needed
Parallel Testsโœ… Nativeโœ… Grid setup needed
Trace Viewerโœ… Built-inโŒ None
Mobile Emulationโœ… Built-in devicesโŒ Limited
Speedโšก FasterSlower
03
Which programming languages does Playwright support?
โ–ผ
JavaScriptTypeScriptPythonJavaC# (.NET)

For QA interviews in India, TypeScript is the most in-demand.
04
Explain the Browser โ†’ Context โ†’ Page hierarchy in Playwright.
โ–ผ
const browser = await chromium.launch(); // browser process const context = await browser.newContext(); // isolated session (cookies/storage) const page = await context.newPage(); // single tab
Browser โ€” actual browser instance.
Context โ€” like incognito session. Multiple contexts = multiple users.
Page โ€” a single tab. All interactions happen here.
05
How do you install and set up Playwright?
โ–ผ
npm init playwright@latest # interactive setup wizard # OR manual install npm install -D @playwright/test npx playwright install # downloads browsers npx playwright install --with-deps # with OS dependencies (for CI)
06
What is a Locator in Playwright? Why is it preferred?
โ–ผ
A Locator is a lazy, auto-waiting reference to an element. It does NOT immediately find the element โ€” it finds it fresh on every action. This means it always works with dynamic DOM.

Why preferred over elementHandle:
โœ… Auto-waits for actionability before actions
โœ… Re-queries DOM on every action (handles dynamic elements)
โœ… Works natively with expect() assertions
โœ… Chainable and filterable
07
Difference between locator() and elementHandle()?
โ–ผ
locator()elementHandle()
Auto-waitโœ… Retries automaticallyโŒ Snapshot, no retry
DOM evaluationLazy โ€” on each actionEager โ€” at call time
Dynamic elementsโœ… Handles perfectlyโŒ Can go stale
Recommendedโœ… AlwaysโŒ Avoid in new code
08
How does Playwright auto-waiting work? What are actionability checks?
โ–ผ
Before performing any action (click, fill, etc.), Playwright automatically waits for the element to pass these actionability checks:

VisibleStable (not animating)EnabledNot obscured

Default timeout: 30 seconds (configurable)
// No manual wait needed โ€” Playwright waits automatically await page.locator('#submit').click(); // waits for visible+enabled+stable
09
Difference between textContent() and innerText()?
โ–ผ
MethodReturnsHidden elements
textContent()All raw text (including hidden)โœ… Included
innerText()Visible text onlyโŒ Excluded
await locator.textContent(); // "Hello hidden" await locator.innerText(); // "Hello"
10
What is playwright.config.ts and what can you configure in it?
โ–ผ
export default defineConfig({ testDir: './tests', timeout: 30000, // per test timeout retries: 2, // retry failed tests workers: 4, // parallel workers fullyParallel: true, reporter: [['html'], ['list']], use: { baseURL: 'https://example.com', headless: true, screenshot: 'only-on-failure', video: 'retain-on-failure', trace: 'retain-on-failure', }, projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, { name: 'firefox', use: { ...devices['Desktop Firefox'] } }, ], });
11
What are the important Playwright CLI commands?
โ–ผ
npx playwright test # run all tests npx playwright test --headed # show browser npx playwright test --ui # interactive UI mode npx playwright test login.spec.ts # specific file npx playwright test --grep "login" # by test name npx playwright test --project=chromium # specific browser npx playwright test --workers=4 # parallel workers npx playwright test --debug # debug mode npx playwright show-report # open HTML report npx playwright codegen https://site.com # record test
12
What are fixtures in Playwright? How do you create custom fixtures?
โ–ผ
Fixtures are reusable setup/teardown objects provided to tests. Built-in fixtures: page, context, browser, request.
// Custom fixture const test = base.extend({ loggedInPage: async ({ page }, use) => { await page.goto('/login'); await page.fill('#email', 'user@test.com'); await page.fill('#pass', 'password'); await page.click('#submit'); await use(page); // provide to test await page.close(); // cleanup }, }); test('dashboard loads', async ({ loggedInPage }) => { await expect(loggedInPage).toHaveURL('/dashboard'); });
13
How do you implement Page Object Model (POM) in Playwright?
โ–ผ
// pages/LoginPage.ts export class LoginPage { readonly emailInput = this.page.getByLabel('Email'); readonly passInput = this.page.getByLabel('Password'); readonly submitBtn = this.page.getByRole('button', { name: 'Login' }); constructor(private page: Page) {} async goto() { await this.page.goto('/login'); } async login(email: string, pass: string) { await this.emailInput.fill(email); await this.passInput.fill(pass); await this.submitBtn.click(); } }
14
What is Playwright Codegen? How do you use it?
โ–ผ
Codegen is Playwright's test recorder. It records your browser actions and generates test code automatically.
npx playwright codegen https://example.com npx playwright codegen --target=python https://site.com npx playwright codegen --save-storage=auth.json https://site.com
15
How do you run tests in multiple browsers simultaneously?
โ–ผ
// playwright.config.ts projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, { name: 'firefox', use: { ...devices['Desktop Firefox'] } }, { name: 'webkit', use: { ...devices['Desktop Safari'] } }, { name: 'mobile', use: { ...devices['iPhone 13'] } }, ],
16
Difference between headless and headed mode?
โ–ผ
ModeDescriptionUse case
HeadlessNo browser UI, fasterCI/CD pipelines
HeadedBrowser visibleDebugging, development
UI ModeInteractive test explorerBest for local dev
npx playwright test # headless (default) npx playwright test --headed # show browser npx playwright test --ui # UI mode
17
Explain test.only(), test.skip(), test.fixme(), test.fail()
โ–ผ
test.only('run only this test', async({ page }) => {}); // only this runs test.skip('skip this test', async({ page }) => {}); // mark as skipped test.fixme('known broken', async({ page }) => {}); // expected to fail, skip test.fail('expected fail', async({ page }) => {}); // expected to fail, runs // Conditional skip test.skip(process.platform === 'win32', 'Windows bug');
18
Explain test hooks: beforeEach, afterEach, beforeAll, afterAll
โ–ผ
test.beforeAll(async () => { // runs ONCE before all tests in describe }); test.beforeEach(async ({ page }) => { await page.goto('/home'); // runs before EVERY test }); test.afterEach(async ({ page }, testInfo) => { if (testInfo.status !== 'passed') await page.screenshot({ path: `fail-${testInfo.title}.png` }); }); test.afterAll(async () => { // cleanup after all tests });
๐ŸŽฏLocators & Selectors14 Qs
19
What are all the built-in locator strategies in Playwright?
โ–ผ
page.getByRole('button', { name: 'Submit' }) // ARIA role โ€” most recommended page.getByText('Login') // exact/partial text page.getByLabel('Email address') // form label page.getByPlaceholder('Enter email') // input placeholder page.getByAltText('Company logo') // img alt text page.getByTitle('Close dialog') // title attribute page.getByTestId('submit-btn') // data-testid โ€” most stable! page.locator('#id') // CSS selector page.locator('xpath=//button') // XPath
๐Ÿ’ก Priority: getByRole > getByTestId > getByLabel > getByText > CSS
20
How do you use filter(), has(), and nth() on locators?
โ–ผ
// filter() by text await page.locator('.product') .filter({ hasText: 'iPhone 15' }).click(); // filter() by child locator await page.locator('.row') .filter({ has: page.locator('.badge') }).click(); // nth() โ€” pick Nth element await page.locator('.item').nth(0).click(); // first await page.locator('.item').last().click(); // last await page.locator('.item').first().click(); // first
21
How do you chain locators? Give examples.
โ–ผ
// Chain โ€” search within a parent const row = page.locator('tr').filter({ hasText: 'John' }); await row.locator('button.delete').click(); // Search inside a section const form = page.locator('form#loginForm'); await form.getByLabel('Email').fill('test@test.com');
22
How do you work with multiple elements (all(), count(), allTextContents())?
โ–ผ
const count = await page.locator('.item').count(); // number of elements const texts = await page.locator('.item').allTextContents(); // ["Item 1", "Item 2", "Item 3"] // Iterate all elements const items = await page.locator('.item').all(); for (const item of items) { console.log(await item.textContent()); }
23
How do you handle dropdown (select) elements?
โ–ผ
// Native HTML select await page.locator('#country').selectOption('India'); // by value await page.locator('#country').selectOption({ label: 'India' }); // by label await page.locator('#country').selectOption({ index: 2 }); // by index // Multi-select await page.locator('#lang').selectOption(['java', 'python']); // Custom dropdown (not native select) await page.locator('#dropdown').click(); await page.locator('.option').filter({ hasText: 'India' }).click();
24
How does Playwright handle Shadow DOM?
โ–ผ
Playwright automatically pierces Shadow DOM โ€” no special handling needed for most selectors.
// Works automatically โ€” Playwright auto-pierces shadow DOM await page.locator('custom-input input').fill('value'); // Also works with getBy methods await page.getByLabel('Name').fill('John'); // even inside shadow DOM
๐Ÿ’ก This is a huge advantage over Selenium where shadow DOM requires complex JS workarounds.
25
How do you handle checkboxes and radio buttons?
โ–ผ
// Checkbox await page.locator('#agree').check(); // check it await page.locator('#agree').uncheck(); // uncheck it await page.locator('#agree').setChecked(true); // set state // Verify state await expect(page.locator('#agree')).toBeChecked(); // Radio button await page.getByRole('radio', { name: 'Male' }).check();
26
How do you handle file upload?
โ–ผ
// Simple file input await page.locator('input[type="file"]').setInputFiles('./test.pdf'); // Multiple files await page.locator('#upload').setInputFiles(['file1.jpg', 'file2.jpg']); // Clear file await page.locator('#upload').setInputFiles([]); // Drag and drop upload โ€” use filechooser event const [fc] = await Promise.all([ page.waitForEvent('filechooser'), page.locator('#dropzone').click() ]); await fc.setFiles('./test.pdf');
27
How do you perform mouse and keyboard actions?
โ–ผ
// Mouse actions await page.locator('#menu').hover(); await page.locator('#item').dblclick(); await page.locator('#el').click({ button: 'right' }); // right-click await page.mouse.move(100, 200); await page.mouse.down(); await page.mouse.up(); // Keyboard await page.locator('#input').press('Enter'); await page.keyboard.press('Control+A'); await page.keyboard.type('Hello World');
28
How do you handle drag and drop?
โ–ผ
// Method 1: dragTo await page.locator('#source').dragTo(page.locator('#target')); // Method 2: manual mouse await page.locator('#source').hover(); await page.mouse.down(); await page.locator('#target').hover(); await page.mouse.up();
29
Difference between page.locator() and page.$()?
โ–ผ
page.locator()page.$()
TypeLazy LocatorElementHandle (snapshot)
Auto-waitโœ… YesโŒ No
Stale riskNone (re-queries)High (can go stale)
Useโœ… Always preferredโŒ Legacy only
30
How do you execute JavaScript in the browser context?
โ–ผ
// page.evaluate โ€” run JS in browser const title = await page.evaluate(() => document.title); // Pass arguments const val = await page.evaluate(n => n * 2, 21); // 42 // locator.evaluate โ€” run JS on specific element const color = await page.locator('h1') .evaluate(el => getComputedStyle(el).color);
31
How do you scroll to an element or scroll the page?
โ–ผ
// Scroll element into view await page.locator('#footer').scrollIntoViewIfNeeded(); // Scroll page await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); // Scroll inside container await page.locator('#scrollable').evaluate(el => el.scrollTo(0, 500));
32
How do you get attribute values, properties, and CSS values?
โ–ผ
await page.locator('a').getAttribute('href'); // "/home" await page.locator('input').inputValue(); // input value await page.locator('input').isChecked(); // boolean await page.locator('button').isEnabled(); // boolean await page.locator('#el').evaluate( el => getComputedStyle(el).backgroundColor // CSS value );
๐ŸชŸFrames, Windows & Alerts10 Qs
33
How do you handle iframes in Playwright?
โ–ผ
// Method 1: frameLocator (recommended) const frame = page.frameLocator('iframe[title="Payment"]'); await frame.locator('#cardNum').fill('4242424242424242'); // Method 2: page.frame() โ€” legacy const f = page.frame({ url: /payment/ }); await f.locator('#cardNum').fill('4242424242424242'); // Nested iframes await page.frameLocator('#outer') .frameLocator('#inner') .locator('button').click();
34
Difference between frameLocator() and page.frame()?
โ–ผ
frameLocator()page.frame()
SelectorCSS/XPath of iframe elementname or URL attribute
Auto-waitโœ… YesโŒ No
ReturnsFrameLocator (chainable)Frame object
Recommendedโœ… ModernLegacy
35
How do you handle multiple browser tabs/windows?
โ–ผ
// Wait for new tab to open const [newPage] = await Promise.all([ context.waitForEvent('page'), page.locator('a[target="_blank"]').click() ]); await newPage.waitForLoadState('domcontentloaded'); console.log(await newPage.url()); // Switch between pages const pages = context.pages(); // array of all open pages await pages[1].bringToFront(); // switch to tab 2 // Close tab await newPage.close();
36
How do you handle JavaScript dialogs (alert, confirm, prompt)?
โ–ผ
// Register handler BEFORE triggering the dialog page.on('dialog', async (dialog) => { console.log(dialog.type()); // 'alert' | 'confirm' | 'prompt' console.log(dialog.message()); // dialog message text if (dialog.type() === 'confirm') { await dialog.accept(); // click OK } else if (dialog.type() === 'prompt') { await dialog.accept('my answer'); // fill prompt + OK } else { await dialog.dismiss(); // click Cancel } }); await page.locator('#deleteBtn').click(); // triggers dialog
37
How do you handle popup windows?
โ–ผ
// Listen for popup window event const [popup] = await Promise.all([ page.waitForEvent('popup'), page.locator('#openPopup').click() ]); await popup.waitForLoadState(); await popup.locator('#submit').click(); await popup.close();
38
How do you handle file downloads?
โ–ผ
// Wait for download to start const [download] = await Promise.all([ page.waitForEvent('download'), page.locator('#downloadBtn').click() ]); console.log(download.suggestedFilename()); // filename await download.saveAs('./downloads/file.pdf'); const path = await download.path(); // temp path
39
What is BrowserContext and why is it important?
โ–ผ
BrowserContext is an isolated browser session โ€” like a separate incognito window with its own cookies, localStorage, and session data. This is perfect for multi-user testing.
// Two isolated users in same test const adminCtx = await browser.newContext({ storageState: 'admin.json' }); const userCtx = await browser.newContext({ storageState: 'user.json' }); const adminPage = await adminCtx.newPage(); const userPage = await userCtx.newPage(); // Both run completely independently
40
How do you handle cookie banners / GDPR popups?
โ–ผ
// Option 1: Click accept in beforeEach test.beforeEach(async ({ page }) => { await page.goto('/'); const banner = page.locator('#cookieBanner'); if (await banner.isVisible()) await page.locator('#acceptCookies').click(); }); // Option 2: Set cookies directly via context await context.addCookies([{ name: 'cookieConsent', value: 'true', domain: 'example.com', path: '/' }]);
41
How do you interact with tooltips?
โ–ผ
// Hover to show tooltip await page.locator('[data-tooltip]').hover(); // Wait for tooltip to appear await expect(page.locator('.tooltip')).toBeVisible(); const text = await page.locator('.tooltip').textContent();
42
How do you intercept and modify network requests?
โ–ผ
// Mock API response await page.route('**/api/users', route => route.fulfill({ json: [{ id: 1, name: 'Test' }] }) ); // Modify response await page.route('**/api/data', async route => { const res = await route.fetch(); const json = await res.json(); json.status = 'modified'; await route.fulfill({ response: res, json }); }); // Abort requests (e.g. block images) await page.route('**/*.{png,jpg,gif}', r => r.abort());
โฑWaits & Assertions12 Qs
43
What are the most important Playwright assertions?
โ–ผ
// Element assertions await expect(locator).toBeVisible() await expect(locator).toBeHidden() await expect(locator).toBeEnabled() await expect(locator).toBeDisabled() await expect(locator).toBeChecked() await expect(locator).toHaveText('Expected') await expect(locator).toContainText('partial') await expect(locator).toHaveValue('input val') await expect(locator).toHaveCount(3) await expect(locator).toHaveAttribute('href', '/home') await expect(locator).toHaveClass('active') // Page assertions await expect(page).toHaveURL('/dashboard') await expect(page).toHaveTitle('My App')
44
Difference between expect().toBeVisible() and locator.isVisible()?
โ–ผ
expect().toBeVisible()locator.isVisible()
TypeAssertion (fails test)Returns boolean
Auto-retryโœ… Retries until timeoutโŒ Instant check
Use caseTest assertionsConditional logic (if/else)
// if modal exists, close it if (await page.locator('#modal').isVisible()) await page.locator('#close').click();
45
How do you do explicit waits in Playwright?
โ–ผ
await page.locator('#loader').waitFor({ state: 'hidden' }); // wait for hidden await page.locator('#result').waitFor({ state: 'visible' }); // wait for visible await page.locator('#result').waitFor({ state: 'attached' }); // wait for DOM await page.waitForURL('**/dashboard'); await page.waitForURL(/checkout/); await page.waitForLoadState('networkidle'); // no network for 500ms await page.waitForLoadState('domcontentloaded'); await page.waitForSelector('#element'); // legacy, use waitFor await page.waitForResponse('**/api/data'); // wait for API call await page.waitForFunction(() => window.loaded === true);
46
What are soft assertions in Playwright?
โ–ผ
Soft assertions do not stop test execution on failure. All soft assertions run, and the test fails at the end if any failed.
const softExpect = expect.soft; await softExpect(page.locator('h1')).toHaveText('Welcome'); await softExpect(page.locator('#count')).toHaveText('5'); await softExpect(page).toHaveTitle('Dashboard'); // Test continues even if some fail, then fails at end
47
How do you wait for an API response during a test?
โ–ผ
// Wait for specific API call to complete const [response] = await Promise.all([ page.waitForResponse('**/api/users'), page.locator('#loadUsers').click() ]); expect(response.status()).toBe(200); // With condition const res = await page.waitForResponse( r => r.url().includes('/api/users') && r.status() === 200 );
48
How do you set custom timeouts per test, element, or assertion?
โ–ผ
// Per test test('slow test', async ({ page }) => { test.setTimeout(60000); // 60 seconds for this test }); // Per assertion await expect(locator).toBeVisible({ timeout: 10000 }); // Per action (waitFor) await locator.waitFor({ state: 'visible', timeout: 15000 }); // Global in config export default { timeout: 30000, expect: { timeout: 5000 } };
49
How do you configure test retries?
โ–ผ
// playwright.config.ts export default { retries: 2, // retry failed tests 2 times }; // Per test test('flaky test', async ({ page }) => { test.info().retries; // current retry count }, { retries: 3 }); // CLI npx playwright test --retries=3
50
How does visual testing (screenshot comparison) work?
โ–ผ
// First run creates baseline screenshot await expect(page).toHaveScreenshot('homepage.png'); await expect(page.locator('#chart')).toHaveScreenshot('chart.png'); // With tolerance for small differences await expect(page).toHaveScreenshot({ maxDiffPixels: 100 }); // Update baselines npx playwright test --update-snapshots
51
How do you listen to page events like console errors?
โ–ผ
page.on('console', msg => console.log(`[${msg.type()}] ${msg.text()}`)); page.on('pageerror', err => console.error('Page error:', err)); page.on('requestfailed', req => console.log('Failed:', req.url())); page.on('response', res => { if (res.status() >= 400) console.error('HTTP Error:', res.url(), res.status()); });
52
How do you poll/wait for a condition with expect.poll()?
โ–ผ
// expect.poll โ€” keep checking until condition passes await expect.poll(async () => { const res = await page.evaluate(() => window.dataLoaded); return res; }, { timeout: 10000, intervals: [500, 1000, 2000] }).toBe(true);
53
How does page.goto() work? What are waitUntil options?
โ–ผ
await page.goto('https://example.com'); // waitUntil options: await page.goto(url, { waitUntil: 'load' }); // load event await page.goto(url, { waitUntil: 'domcontentloaded'}); // DOM ready await page.goto(url, { waitUntil: 'networkidle' }); // no network 500ms await page.goto(url, { waitUntil: 'commit' }); // first byte received await page.goto(url, { timeout: 60000 }); // custom timeout
54
How do you write negative assertions?
โ–ผ
await expect(locator).not.toBeVisible(); await expect(locator).not.toHaveText('Error'); await expect(locator).not.toBeEnabled(); await expect(page).not.toHaveURL('/error');
โš™๏ธTest Runner & Configuration12 Qs
55
How do you run tests in parallel? What is fullyParallel?
โ–ผ
// playwright.config.ts export default { workers: 4, // 4 parallel workers (default = CPU count / 2) fullyParallel: true, // tests in same FILE also run in parallel }; // fullyParallel: false (default) // โ†’ tests within a file run SEQUENTIALLY, files run in parallel // fullyParallel: true // โ†’ ALL tests run in parallel including same-file tests // Force serial for a describe block test.describe.configure({ mode: 'serial' });
56
How do you configure test reporters?
โ–ผ
// playwright.config.ts reporter: [ ['html', { outputFolder: 'playwright-report', open: 'never' }], ['junit', { outputFile: 'junit-results.xml' }], ['json', { outputFile: 'results.json' }], ['list'], // console list ['dot'], // minimal dots output ], // View HTML report npx playwright show-report
57
How do you group tests and run specific groups?
โ–ผ
// Group with describe test.describe('Login Tests', () => { test('valid login', async({ page }) => {}); test('invalid password', async({ page }) => {}); }); // Tag tests (Playwright v1.42+) test('smoke test @smoke', async({ page }) => {}); test('regression @regression', async({ page }) => {}); // Run by grep (CLI) npx playwright test --grep "@smoke" npx playwright test --grep-invert "@regression" # exclude
58
How do you write data-driven / parameterized tests?
โ–ผ
const testData = [ { user: 'admin', role: 'ADMIN', redirect: '/admin' }, { user: 'guest', role: 'GUEST', redirect: '/home' }, { user: 'mod', role: 'MOD', redirect: '/mod' }, ]; for (const { user, role, redirect } of testData) { test(`login as ${user}`, async ({ page }) => { await page.goto('/login'); await page.fill('#user', user); await page.click('#submit'); await expect(page).toHaveURL(redirect); }); }
59
How do you use environment variables and baseURL?
โ–ผ
// .env file BASE_URL=https://staging.example.com // playwright.config.ts import { defineConfig } from '@playwright/test'; import dotenv from 'dotenv'; dotenv.config(); export default defineConfig({ use: { baseURL: process.env.BASE_URL || 'https://example.com' } }); // In test โ€” use relative URLs await page.goto('/login'); // resolves to baseURL/login
60
When should you use serial mode vs parallel mode?
โ–ผ
Parallel (default): Tests are isolated and independent. Most tests should be parallel.

Serial mode: Tests depend on each other and share state (e.g., multi-step workflow).
test.describe.configure({ mode: 'serial' }); test.describe('Checkout flow', () => { test('1. Add to cart', ...); test('2. Apply coupon', ...); // depends on step 1 test('3. Pay', ...); // depends on steps 1+2 });
61
What is globalSetup and globalTeardown?
โ–ผ
// playwright.config.ts export default { globalSetup: './global-setup.ts', globalTeardown: './global-teardown.ts', }; // global-setup.ts โ€” runs ONCE before all test files export default async function setup() { // seed DB, start mock server, login and save auth const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto('/login'); // ... login ... await page.context().storageState({ path: 'auth.json' }); await browser.close(); }
62
What are project dependencies in Playwright config?
โ–ผ
// Run setup project first, then tests projects: [ { name: 'setup', testMatch: '**/auth.setup.ts' }, { name: 'chromium', dependencies: ['setup'], // runs after setup use: { storageState: 'auth.json' } } ]
63
How do you use testInfo to add annotations and attachments?
โ–ผ
test('my test', async ({ page }, testInfo) => { // Add annotation testInfo.annotations.push({ type: 'issue', description: 'BUG-123' }); // Attach screenshot const buf = await page.screenshot(); await testInfo.attach('screenshot', { body: buf, contentType: 'image/png' }); // Check retry count console.log(testInfo.retry); // 0, 1, 2... console.log(testInfo.status); // passed/failed/timedOut });
64
How do you debug failing tests?
โ–ผ
npx playwright test --debug # step-by-step inspector npx playwright test --headed # see browser npx playwright test --ui # UI mode (best option!) PWDEBUG=1 npx playwright test # Inspector with breakpoints // In config โ€” slow down actions use: { slowMo: 500 } // 500ms delay between actions // In test โ€” pause execution await page.pause(); // opens Inspector at this point
65
How do you configure screenshots and videos?
โ–ผ
export default { use: { screenshot: 'only-on-failure', // 'on' | 'off' | 'only-on-failure' video: 'retain-on-failure', // 'on' | 'off' | 'retain-on-failure' trace: 'retain-on-failure', // 'on' | 'off' | 'retain-on-failure' } }; // Manual screenshot in test await page.screenshot({ path: 'ss.png', fullPage: true }); await page.locator('#chart').screenshot({ path: 'chart.png' });
66
Different timeout types in Playwright โ€” explain all.
โ–ผ
Timeout TypeDefaultConfig Key
Test timeout30stimeout
Expect timeout5sexpect.timeout
Action timeoutsame as testuse.actionTimeout
Navigation timeoutsame as testuse.navigationTimeout
๐Ÿš€Advanced Topics14 Qs
67
How do you handle authentication using storageState?
โ–ผ
// auth.setup.ts โ€” login once, save state test('authenticate', async ({ page }) => { await page.goto('/login'); await page.fill('#email', process.env.TEST_EMAIL!); await page.fill('#pass', process.env.TEST_PASS!); await page.click('#submit'); await page.context().storageState({ path: 'auth.json' }); }); // playwright.config.ts โ€” reuse in all tests use: { storageState: 'auth.json' } // All tests now skip login โ€” they start already logged in!
๐Ÿ’ก This saves huge time in large test suites. Login once, reuse everywhere.
68
How do you handle Bearer tokens and Basic Auth?
โ–ผ
// Basic Auth (popup) const context = await browser.newContext({ httpCredentials: { username: 'admin', password: 'secret' } }); // Bearer token via header const context = await browser.newContext({ extraHTTPHeaders: { 'Authorization': `Bearer ${process.env.API_TOKEN}` } });
69
What is Playwright Tracing? How do you use the Trace Viewer?
โ–ผ
Trace records everything โ€” DOM snapshots, network calls, console logs, screenshots โ€” for every action. Like a "time-travel debugger".
// Start tracing await context.tracing.start({ screenshots: true, snapshots: true }); // ... run test ... await context.tracing.stop({ path: 'trace.zip' }); // View trace npx playwright show-trace trace.zip // Auto capture in config use: { trace: 'retain-on-failure' }
70
How do you do mobile emulation in Playwright?
โ–ผ
import { devices } from '@playwright/test'; // Using built-in devices const context = await browser.newContext({ ...devices['iPhone 13'] // includes viewport, userAgent, touch }); // Custom viewport const context = await browser.newContext({ viewport: { width: 375, height: 812 }, userAgent: 'Mozilla/5.0 (iPhone...)', isMobile: true, hasTouch: true, }); // In config project { name: 'Mobile Chrome', use: { ...devices['Pixel 5'] } }
71
How do you emulate geolocation, timezone, and locale?
โ–ผ
const context = await browser.newContext({ geolocation: { longitude: 77.59, latitude: 12.97 }, // Bangalore permissions: ['geolocation'], locale: 'en-IN', timezoneId: 'Asia/Kolkata', colorScheme: 'dark', });
72
How do you bypass bot detection in Playwright?
โ–ผ
const browser = await chromium.launch({ args: [ '--disable-blink-features=AutomationControlled', '--disable-features=IsolateOrigins' ] }); const context = await browser.newContext({ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit...' }); // Remove webdriver flag await context.addInitScript(() => { Object.defineProperty(navigator, 'webdriver', { get: () => false }); });
73
How do you do accessibility testing with Playwright?
โ–ผ
npm install @axe-core/playwright import AxeBuilder from '@axe-core/playwright'; test('no a11y violations', async ({ page }) => { await page.goto('/'); const results = await new AxeBuilder({ page }).analyze(); expect(results.violations).toHaveLength(0); }); // Playwright also has built-in ARIA snapshot await expect(page.locator('main')).toMatchAriaSnapshot(` - heading "Dashboard" - button "Logout" `);
74
How do you simulate slow network conditions?
โ–ผ
// Simulate Slow 3G const client = await page.context().newCDPSession(page); await client.send('Network.emulateNetworkConditions', { offline: false, latency: 400, // ms downloadThroughput: 500 * 1024 / 8, // bytes/s uploadThroughput: 500 * 1024 / 8, });
75
How do you handle test data cleanup and database seeding?
โ–ผ
// Use API to set up test data quickly test.beforeEach(async ({ request }) => { // Seed via API โ€” faster than UI await request.post('/api/test/seed', { data: { user: 'testuser', role: 'admin' } }); }); test.afterEach(async ({ request }) => { // Cleanup via API await request.delete('/api/test/cleanup'); });
76
What is CDP (Chrome DevTools Protocol) in Playwright? When do you use it?
โ–ผ
// CDP gives low-level browser control (Chromium only) const client = await page.context().newCDPSession(page); // Examples: network throttling, heap snapshots, coverage await client.send('Performance.enable'); await client.send('Network.enable'); // Get performance metrics const metrics = await client.send('Performance.getMetrics');
77
How do you share state between tests safely?
โ–ผ
// Worker-scoped fixtures โ€” shared within a worker const test = base.extend({ dbConnection: [async ({}, use) => { const db = await connectDB(); await use(db); await db.close(); }, { scope: 'worker' }], // shared across tests in same worker });
78
How do you block third-party requests (analytics, ads)?
โ–ผ
// Block all analytics/tracking await page.route('**/{analytics,gtag,pixel,hotjar}/**', r => r.abort()); // Block by domain await page.route('**', (route) => { if (route.request().url().includes('google-analytics.com')) return route.abort(); route.continue(); });
79
What is addInitScript and when do you use it?
โ–ผ
addInitScript injects JavaScript that runs before any page scripts. Useful for mocking browser APIs, faking dates, disabling animations.
// Mock Date.now() to fix date await page.addInitScript(() => { Date.now = () => new Date('2026-01-01').getTime(); }); // Disable animations await page.addInitScript(() => { window.matchMedia = () => ({ matches: false }); });
80
How do you ensure test isolation in parallel execution?
โ–ผ
Each test should be completely independent. Best practices:
  • Create fresh context per test (default behavior)
  • Use API to reset data in beforeEach
  • Use unique test data (e.g., email + timestamp)
  • Never share browser page between tests
  • Use storageState instead of UI login
// Unique data per test const email = `test+${Date.now()}@example.com`;
๐Ÿ”—API Testing with Playwright10 Qs
81
How do you do API testing with Playwright's request fixture?
โ–ผ
test('GET /api/users', async ({ request }) => { const res = await request.get('https://api.example.com/users'); expect(res.status()).toBe(200); expect(res.ok()).toBeTruthy(); const body = await res.json(); expect(body).toHaveProperty('users'); expect(body.users).toHaveLength(10); });
82
How do you send POST, PUT, DELETE requests?
โ–ผ
// POST with JSON body const res = await request.post('/api/users', { data: { name: 'John', email: 'john@test.com' }, headers: { 'Content-Type': 'application/json' } }); expect(res.status()).toBe(201); const user = await res.json(); // PUT await request.put(`/api/users/${user.id}`, { data: { name: 'Jane' } }); // DELETE const del = await request.delete(`/api/users/${user.id}`); expect(del.status()).toBe(204);
83
How do you create a reusable API context with auth headers?
โ–ผ
// Create APIRequestContext with base URL + token const apiContext = await playwright.request.newContext({ baseURL: 'https://api.example.com', extraHTTPHeaders: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json' }, }); // Now just use relative paths const res = await apiContext.get('/users'); // Always dispose after use await apiContext.dispose();
84
How do you mock API responses using page.route()?
โ–ผ
// Simple JSON mock await page.route('**/api/products', route => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify([{ id: 1, name: 'Laptop', price: 50000 }]) }) ); // Mock error response await page.route('**/api/checkout', route => route.fulfill({ status: 500, json: { error: 'Server Error' } }) );
85
What can you assert on API responses?
โ–ผ
const res = await request.get('/api/users/1'); expect(res.status()).toBe(200); expect(res.ok()).toBeTruthy(); expect(res.headers()['content-type']).toContain('application/json'); const body = await res.json(); expect(body.id).toBe(1); expect(body.name).toBeTruthy(); expect(body).toMatchObject({ id: 1, email: expect.stringContaining('@') });
86
How do you send form data or multipart data in API tests?
โ–ผ
// Form data const res = await request.post('/api/login', { form: { username: 'admin', password: 'secret' } }); // Multipart (file upload via API) const res = await request.post('/api/upload', { multipart: { file: { name: 'test.pdf', mimeType: 'application/pdf', buffer: fs.readFileSync('test.pdf') }, description: 'Test document' } }); expect(res.status()).toBe(200);
87
How do you combine UI and API testing in one test?
โ–ผ
test('create via API, verify in UI', async ({ page, request }) => { // Create data via API (fast) const res = await request.post('/api/products', { data: { name: 'Test Product', price: 999 } }); const { id } = await res.json(); // Verify in UI await page.goto(`/products/${id}`); await expect(page.locator('h1')).toHaveText('Test Product'); });
88
How do you monitor and capture all network requests?
โ–ผ
const apiCalls: string[] = []; page.on('request', req => { if (req.url().includes('/api')) apiCalls.push(`${req.method()} ${req.url()}`); }); page.on('response', res => { console.log(res.status(), res.url()); }); await page.goto('/dashboard'); console.log('API calls made:', apiCalls);
89
How do you test GraphQL APIs with Playwright?
โ–ผ
// GraphQL query via request const res = await request.post('/graphql', { data: { query: `query GetUser($id: ID!) { user(id: $id) { name email } }`, variables: { id: '1' } } }); const { data } = await res.json(); expect(data.user.name).toBe('John'); // Mock GraphQL response await page.route('**/graphql', route => route.fulfill({ json: { data: { user: { name: 'Mock User' } } } }) );
90
How do you validate API response schema?
โ–ผ
// Using Jest matchers (built-in) const body = await res.json(); expect(body).toMatchObject({ id: expect.any(Number), name: expect.any(String), email: expect.stringMatching(/^[^\s@]+@[^\s@]+\.[^\s@]+$/), createdAt: expect.any(String), }); // Using Zod for strict schema validation import { z } from 'zod'; const UserSchema = z.object({ id: z.number(), name: z.string() }); expect(() => UserSchema.parse(body)).not.toThrow();
๐Ÿ”„CI/CD, Debug & Real-World11 Qs
91
How do you run Playwright in GitHub Actions CI/CD?
โ–ผ
name: Playwright Tests on: [push, pull_request] jobs: playwright: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: '20' } - run: npm ci - run: npx playwright install --with-deps - run: npx playwright test - uses: actions/upload-artifact@v4 if: always() # upload even on failure! with: name: playwright-report path: playwright-report/ retention-days: 30
92
How do you run Playwright in Jenkins?
โ–ผ
// Jenkinsfile (Declarative) pipeline { agent { docker { image 'mcr.microsoft.com/playwright:v1.44.0-jammy' } } stages { stage('Install') { steps { sh 'npm ci' } } stage('Test') { steps { sh 'npx playwright test' } post { always { publishHTML(target: [ reportDir: 'playwright-report', reportFiles: 'index.html', reportName: 'Playwright Report' ]) } } } } }
93
How do you run Playwright tests in Docker?
โ–ผ
# Use official Playwright Docker image (has all browsers preinstalled) docker pull mcr.microsoft.com/playwright:v1.44.0-jammy docker run --rm -v $(pwd):/app -w /app \ mcr.microsoft.com/playwright:v1.44.0-jammy \ npx playwright test # Dockerfile FROM mcr.microsoft.com/playwright:v1.44.0-jammy WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . CMD ["npx", "playwright", "test"]
94
How do you identify and fix flaky tests?
โ–ผ
Common causes of flaky tests and fixes:
ProblemFix
Hardcoded sleepUse waitFor / expect assertions
Race conditionWait for network/URL/element state
Shared stateUse fresh context per test
External APIMock the API call
Timing issuesUse expect() auto-retry, not isVisible()
// Bad โ€” fixed sleep await page.waitForTimeout(3000); // Good โ€” wait for actual state await expect(page.locator('#result')).toBeVisible();
95
How do you integrate Allure reports with Playwright?
โ–ผ
npm install -D allure-playwright // playwright.config.ts reporter: [['allure-playwright']], // Generate and open Allure report npx playwright test allure generate allure-results --clean -o allure-report allure open allure-report
96
What are best practices for POM in Playwright?
โ–ผ
  • Define locators as readonly properties โ€” not in methods
  • Use constructor injection โ€” pass Page in constructor
  • Methods should be action-based: login(), addToCart()
  • Don't put assertions in page objects โ€” keep them in tests
  • Use getBy* locators for stability
  • Create an index file to export all pages
97
How do you handle errors gracefully in Playwright tests?
โ–ผ
// Catch and handle expected errors try { await page.locator('#popup-close').click({ timeout: 2000 }); } catch { // popup didn't appear, continue test } // Use isVisible() for conditional elements const cookieBanner = page.locator('#cookie-accept'); if (await cookieBanner.isVisible()) await cookieBanner.click();
98
How do you use VS Code Playwright Extension?
โ–ผ
Install: Playwright Test for VSCode by Microsoft

Features:
โœ… Run/debug tests directly from VS Code sidebar
โœ… Click test names to run individual tests
โœ… Pick locator โ€” click on element, get the best locator
โœ… Record tests with Codegen inside VS Code
โœ… Set breakpoints and debug line by line
99
Why did you choose Playwright over Selenium for your project?
โ–ผ
(Common interview question โ€” model answer)

"We chose Playwright because of its auto-waiting capabilities which eliminated most of our flaky test issues. The built-in network interception allowed us to mock API responses for testing edge cases without changing the backend. We also use storageState to skip login in every test, reducing overall test run time by 40%. The Trace Viewer significantly reduced debugging time. TypeScript support gave us type safety throughout our test code."
100
Where does Playwright fit in the testing pyramid?
โ–ผ
Playwright is used primarily for:

๐Ÿ”บ End-to-End (E2E) Tests โ€” User workflows across the entire application
๐Ÿ”บ Integration Tests โ€” Multiple components working together
๐Ÿ”บ API Tests โ€” REST/GraphQL endpoint validation
๐Ÿ”บ Visual Tests โ€” Screenshot comparison

It should NOT replace unit tests (use Jest/Vitest for those). Best practice: fewer E2E tests covering critical paths, more unit tests for logic.
101
What are some recent Playwright features you know about?
โ–ผ
v1.44+ Test tagging with @tag
v1.43+ ARIA snapshots for accessibility testing
v1.42+ UI mode improvements โ€” filter by tags
v1.40+ web-first assertions improvements
v1.38+ Improved trace viewer
v1.35+ Component testing (experimental)

Tip for interviews: Always say you follow the Playwright changelog at playwright.dev/docs/release-notes