๐ŸŽญ Next Gen QA

Playwright
Interview Questions

Complete preparation guide โ€” Basic to Advanced

๐ŸŽฏ 40+ Questions
๐Ÿ“‚ 6 Categories
๐Ÿ‘จโ€๐Ÿ’ป Khan Sir โ€” Next Gen QA
๐Ÿ“ž 8700350994
40+
Total Questions
6
Categories
100%
With Code Examples
Free
Resource
๐Ÿ”
๐Ÿ”น Basic Questions 9 Questions
01
What is Playwright? How is it different from Selenium?
โ–ผ
Playwright is a modern browser automation framework by Microsoft. It supports Chromium, Firefox, and WebKit with a single API.
FeaturePlaywrightSelenium
Auto-waitโœ… Built-inโŒ Manual waits needed
BrowsersChromium, Firefox, WebKitAll browsers via WebDriver
SpeedFasterSlower
Network Mockโœ… Built-inโŒ 3rd party needed
Trace/Debugโœ… Trace ViewerโŒ Limited
LanguageJS/TS, Python, Java, C#Same + more
02
Which languages does Playwright support?
โ–ผ
Playwright officially supports:

JavaScript/TypeScript Python Java C# (.NET)

For QA roles in India, JavaScript/TypeScript is most commonly asked in interviews.
03
What is page, context, and browser in Playwright?
โ–ผ
These are the 3 core objects in Playwright โ€” nested hierarchy:
// browser โ†’ context โ†’ page const browser = await chromium.launch(); // Browser process const context = await browser.newContext(); // Isolated session (cookies, storage) const page = await context.newPage(); // A single tab
Browser โ€” the actual browser instance (Chromium/Firefox/WebKit)
Context โ€” like an incognito window. Each context has its own cookies, localStorage, sessions. Used for multi-user testing.
Page โ€” a single browser tab/window. Most interactions happen here.
04
Difference between locator() and elementHandle()?
โ–ผ
Featurelocator()elementHandle()
Auto-waitโœ… Yes โ€” retries automaticallyโŒ No โ€” snapshot at that moment
Lazyโœ… Evaluated on actionโŒ Resolved immediately
Recommendedโœ… Yes (modern)โŒ Legacy, avoid
Use caseAll normal interactionsOnly if you need JS handle
๐Ÿ’ก Always prefer locator() over elementHandle() in modern Playwright.
05
How does Playwright handle auto-waiting?
โ–ผ
Playwright automatically waits for elements to be in the right state before performing actions. This is called actionability checks.

Before click(), Playwright checks: visible stable enabled not obscured
// No manual wait needed โ€” Playwright waits automatically await page.locator('#submit').click(); // waits until button is visible + enabled // Default timeout: 30 seconds (configurable in playwright.config)
06
What is the difference between textContent() and innerText()?
โ–ผ
MethodWhat it returnsHidden elements
textContent()Raw text including hidden elementsโœ… Included
innerText()Visible text only (human-readable)โŒ Excluded
// If element has hidden span inside: await page.locator('#msg').textContent(); // "Hello hidden" await page.locator('#msg').innerText(); // "Hello" (hidden text ignored)
07
What are frameLocator and page.frame()? When to use which?
โ–ผ
frameLocator() โ€” modern, chainable, uses CSS/XPath selector. Preferred approach.
page.frame() โ€” legacy, uses name or URL attribute.
// frameLocator โ€” preferred (modern) await page.frameLocator('iframe#payment') .locator('#cardNumber').fill('4242424242424242'); // page.frame() โ€” legacy const frame = page.frame({ name: 'paymentFrame' }); await frame.locator('#cardNumber').fill('4242424242424242');
08
How do you run tests in multiple browsers?
โ–ผ
// playwright.config.ts export default { projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, { name: 'firefox', use: { ...devices['Desktop Firefox'] } }, { name: 'webkit', use: { ...devices['Desktop Safari'] } }, ], }; // Run specific browser from CLI npx playwright test --project=chromium npx playwright test --project=firefox
09
Difference between page.locator() vs page.$()?
โ–ผ
page.$() is a shorthand for page.querySelector() โ€” returns an ElementHandle immediately (snapshot). page.locator() is lazy and auto-waits.
page.locator()page.$()
ReturnsLocator (lazy)ElementHandle (snapshot)
Auto-waitโœ… YesโŒ No
Recommendedโœ… AlwaysโŒ Avoid
๐ŸŽฏ Locators & Selectors 6 Questions
10
What is the benefit of using locator over elementHandle?
โ–ผ
Locator advantages:
โœ… Auto-waits for actionability
โœ… Lazy โ€” re-queries DOM on every action (handles dynamic elements)
โœ… Chainable โ€” locator('.list').locator('.item')
โœ… Works with expect() assertions natively
โœ… Supports all Playwright built-in selectors (role, text, label, etc.)
11
How do you handle dynamic elements in Playwright?
โ–ผ
// 1. Use role-based locators (most stable) await page.getByRole('button', { name: 'Submit' }).click(); // 2. Use text locator await page.getByText('Login').click(); // 3. waitFor state await page.locator('#loader').waitFor({ state: 'hidden' }); // 4. Use filter() for dynamic list items await page.locator('.product') .filter({ hasText: 'iPhone 15' }) .click();
12
Difference between allTextContents() and textContent()?
โ–ผ
// textContent() โ€” single element const text = await page.locator('h1').textContent(); // "Welcome" // allTextContents() โ€” ALL matching elements โ†’ returns array const items = await page.locator('.list-item').allTextContents(); // ["Item 1", "Item 2", "Item 3"]
13
How to select options from a dropdown?
โ–ผ
// selectOption() โ€” HTML select element 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 // Custom dropdown (not native select) await page.locator('#dropdown-toggle').click(); await page.locator('.dropdown-item').filter({ hasText: 'India' }).click();
14
How to handle shadow DOM in Playwright?
โ–ผ
Playwright automatically pierces shadow DOM โ€” no special handling needed for most cases!
// Playwright auto-pierces shadow DOM await page.locator('#shadow-input').fill('test'); // If needed, use >> for explicit pierce await page.locator('custom-element >> input').fill('value');
๐Ÿ’ก This is one of Playwright's biggest advantages over Selenium where shadow DOM is painful.
15
What are the built-in locator strategies in Playwright?
โ–ผ
getByRole('button', { name: 'Submit' }) // ARIA role โ€” most recommended getByText('Login') // exact or partial text getByLabel('Email') // form label getByPlaceholder('Enter email') // input placeholder getByAltText('Company logo') // img alt text getByTitle('Close dialog') // title attribute getByTestId('submit-btn') // data-testid (most stable!)
๐ŸชŸ Frames, Windows & Alerts 4 Questions
16
How do you handle iframes in Playwright?
โ–ผ
// Method 1: frameLocator (recommended) const frame = page.frameLocator('iframe[title="Payment Form"]'); await frame.locator('#cardNumber').fill('4242 4242 4242 4242'); // Method 2: page.frame() โ€” legacy const iframe = page.frame({ url: /payment/ }); await iframe.locator('#cardNumber').fill('4242 4242 4242 4242'); // Nested iframes await page.frameLocator('#outer') .frameLocator('#inner') .locator('button').click();
17
How to handle multiple browser tabs/windows?
โ–ผ
// Wait for new page (tab) to open const [newPage] = await Promise.all([ context.waitForEvent('page'), page.locator('a[target="_blank"]').click() ]); await newPage.waitForLoadState(); await newPage.locator('h1').textContent(); // Get all open pages const pages = context.pages(); // array of all pages
18
How do you handle alerts, confirm, and prompt dialogs?
โ–ผ
// Handle dialog BEFORE the action that triggers it page.on('dialog', async dialog => { console.log(dialog.message()); // alert message console.log(dialog.type()); // alert / confirm / prompt await dialog.accept(); // click OK // await dialog.dismiss(); // click Cancel // await dialog.accept('my input'); // for prompt }); await page.locator('#deleteBtn').click(); // triggers confirm dialog
19
Difference between frameLocator() and frame()?
โ–ผ
frameLocator()page.frame()
SelectorCSS/XPath of iframe elementname or URL attribute
ReturnsFrameLocator (lazy, chainable)Frame object
Auto-waitโœ… YesโŒ No
Recommendedโœ… Modern approachLegacy
โฑ Assertions & Waits 3 Questions
20
Difference between expect(locator).toBeVisible() and locator.isVisible()?
โ–ผ
expect().toBeVisible()locator.isVisible()
TypeAssertion (test fails if wrong)Returns boolean
Auto-retryโœ… Yes โ€” retries until timeoutโŒ No โ€” instant check
Use caseAssertions in testConditional logic
// Assertion โ€” retries automatically, fails test if not visible await expect(page.locator('#success')).toBeVisible(); // Boolean โ€” instant, use for if/else logic const visible = await page.locator('#modal').isVisible(); if (visible) { await page.locator('#close').click(); }
21
How do you wait for an element explicitly?
โ–ผ
// waitFor โ€” explicit wait with state await page.locator('#loader').waitFor({ state: 'hidden' }); await page.locator('#result').waitFor({ state: 'visible' }); // Wait for navigation await page.waitForURL('**/dashboard'); await page.waitForLoadState('networkidle'); // Custom wait โ€” wait until condition is true await page.waitForFunction(() => document.title.includes('Done')); // Common assertion waits await expect(page.locator('#count')).toHaveText('5 items'); // retries
22
What are the most common Playwright assertions?
โ–ผ
expect(locator).toBeVisible() expect(locator).toBeHidden() expect(locator).toBeEnabled() expect(locator).toBeDisabled() expect(locator).toBeChecked() expect(locator).toHaveText('Expected text') expect(locator).toContainText('partial text') expect(locator).toHaveValue('input value') expect(locator).toHaveCount(3) expect(locator).toHaveAttribute('href', '/home') expect(page).toHaveURL('/dashboard') expect(page).toHaveTitle('My App')
โš™๏ธ Test Runner & Config 5 Questions
23
How do you run only one test?
โ–ผ
// 1. test.only โ€” in code test.only('login test', async ({ page }) => { ... }); // 2. --grep flag โ€” run by test name pattern npx playwright test --grep "login" // 3. Run specific file npx playwright test tests/login.spec.ts // 4. Run specific line number npx playwright test tests/login.spec.ts:15
24
How do you group tests?
โ–ผ
// test.describe โ€” group related tests test.describe('Login functionality', () => { test.beforeEach(async ({ page }) => { await page.goto('https://example.com/login'); }); test('valid login', async ({ page }) => { ... }); test('invalid password', async ({ page }) => { ... }); test('empty fields', async ({ page }) => { ... }); });
25
Difference between test.beforeEach and test.beforeAll?
โ–ผ
HookRunsUse case
beforeEachBefore EVERY testNavigate to page, login, reset state
afterEachAfter EVERY testCleanup, logout, close modals
beforeAllOnce before all tests in describeDB setup, create test data
afterAllOnce after all testsDB cleanup, close connections
๐Ÿ’ก beforeAll shares state between tests โ€” use carefully! beforeEach is safer for isolated tests.
26
How to run Playwright tests in parallel?
โ–ผ
// playwright.config.ts export default { workers: 4, // 4 parallel workers fullyParallel: true, // run tests in same file in parallel }; // CLI โ€” set workers from command line npx playwright test --workers=4 // Disable parallel for a specific describe test.describe.configure({ mode: 'serial' }); // Force single worker npx playwright test --workers=1
27
How to generate HTML reports in Playwright?
โ–ผ
// playwright.config.ts export default { reporter: [ ['html', { open: 'never' }], // HTML report ['list'], // console output ['json', { outputFile: 'results.json' }] ], }; // Generate and open report npx playwright test npx playwright show-report // opens browser with report
๐Ÿš€ Advanced Topics 8 Questions
28
How do you handle API testing in Playwright?
โ–ผ
// Using APIRequestContext const response = await request.get('https://api.example.com/users'); expect(response.status()).toBe(200); const body = await response.json(); expect(body.users).toHaveLength(10); // POST request const res = await request.post('/api/login', { data: { email: 'test@test.com', password: '123456' } }); expect(res.status()).toBe(200);
29
How do you mock API responses in Playwright?
โ–ผ
// route.fulfill() โ€” intercept and mock API await page.route('**/api/users', async route => { await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify([{ id: 1, name: 'Test User' }]) }); }); // Abort a request await page.route('**/*.png', route => route.abort()); // Modify response await page.route('**/api/data', async route => { const response = await route.fetch(); const json = await response.json(); json.status = 'modified'; await route.fulfill({ response, json }); });
30
How do you take screenshots and videos?
โ–ผ
// Screenshots await page.screenshot({ path: 'screenshot.png' }); await page.screenshot({ path: 'full.png', fullPage: true }); await page.locator('#chart').screenshot({ path: 'chart.png' }); // Videos in config export default { use: { screenshot: 'only-on-failure', // or 'on', 'off' video: 'retain-on-failure', // or 'on', 'off' trace: 'retain-on-failure', // or 'on', 'off' } };
31
How do you run Playwright tests in CI/CD pipeline?
โ–ผ
# GitHub Actions โ€” .github/workflows/playwright.yml name: Playwright Tests on: [push, pull_request] jobs: test: 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() with: name: playwright-report path: playwright-report/
๐Ÿ’ก Always use --with-deps in CI to install browser OS dependencies on Linux.
32
What is tracing in Playwright and how is it useful?
โ–ผ
Trace records everything โ€” DOM snapshots, network requests, console logs, screenshots โ€” for full test debugging. Like a "time-travel debugger".
// Enable tracing await context.tracing.start({ screenshots: true, snapshots: true }); await page.goto('https://example.com'); // ... test steps ... await context.tracing.stop({ path: 'trace.zip' }); // View trace in browser npx playwright show-trace trace.zip // In config (auto trace on failure) use: { trace: 'retain-on-failure' }
33
How do you handle authentication โ€” basic auth, bearer tokens, storageState?
โ–ผ
// 1. Basic Auth const context = await browser.newContext({ httpCredentials: { username: 'admin', password: 'pass123' } }); // 2. Bearer token via extra headers const context = await browser.newContext({ extraHTTPHeaders: { 'Authorization': 'Bearer your_token_here' } }); // 3. storageState โ€” save login state once, reuse in all tests // Step 1: Save auth state await page.goto('/login'); await page.locator('#email').fill('user@test.com'); await page.locator('#submit').click(); await context.storageState({ path: 'auth.json' }); // Step 2: Reuse in all tests (skip login) export default { use: { storageState: 'auth.json' } };
๐Ÿ’ก storageState is a major time-saver โ€” login once, skip login in all other tests!
34
How to run tests in headless vs headed mode?
โ–ผ
// CLI npx playwright test // headless (default) npx playwright test --headed // headed (shows browser) npx playwright test --ui // Playwright UI mode (best for debug) // playwright.config.ts use: { headless: false, // always headed slowMo: 500, // slow down 500ms per action (debug) }
๐Ÿ’ก Headless = no UI, faster, for CI/CD. Headed = shows browser, for debugging. UI mode = best for local development.
35
How to implement Page Object Model (POM) in Playwright?
โ–ผ
// pages/LoginPage.ts export class LoginPage { constructor(private page: Page) {} async goto() { await this.page.goto('/login'); } async login(email: string, password: string) { await this.page.getByLabel('Email').fill(email); await this.page.getByLabel('Password').fill(password); await this.page.getByRole('button', { name: 'Login' }).click(); } } // tests/login.spec.ts test('user can login', async ({ page }) => { const loginPage = new LoginPage(page); await loginPage.goto(); await loginPage.login('user@test.com', 'password'); await expect(page).toHaveURL('/dashboard'); });