Playwright Interview Cheat Sheet: Quick Revision Guide for QA Automation Interviews

Introduction: How to Use This Playwright Interview Cheat Sheet

This Playwright interview cheat sheet is designed for candidates who need a fast, practical revision guide before a QA Automation or SDET interview.

Instead of reading long tutorials, use this guide to quickly revise:

Last-minute revision strategy

Before an interview:

  1. Revise architecture and locators.
  2. Practice the TypeScript snippets.
  3. Review common errors.
  4. Practice scenario-based answers.
  5. Explain why you chose a particular solution.

A strong candidate does not just know Playwright syntax. They understand why a test is reliable, how it can fail, and how the framework can scale.


1. Playwright Fundamentals Quick Reference

Concept → What to Remember → Interview Tip

ConceptQuick Answer
PlaywrightModern browser automation and testing framework
Supported browsersChromium, Firefox, WebKit
LanguagesTypeScript/JavaScript, Python, Java, .NET
Test runnerPlaywright Test
BrowserBrowser process
BrowserContextIsolated browser session
PageBrowser tab
LocatorElement abstraction with waiting/retryability
FixtureReusable test dependency/setup
POMEncapsulates page behavior
TraceDetailed test execution artifact
WorkerParallel test execution process
ShardingSplitting tests across CI jobs

Interview Tip

Remember the basic hierarchy:

Browser → BrowserContext → Page → Locator → Action/Assertion


2. Installation and Project Setup Commands

Concept → Command → Interview Tip

Install Playwright

npm init playwright@latest

Install package

npm install -D @playwright/test

Install browsers

npx playwright install

Install browsers with Linux dependencies

npx playwright install –with-deps

Run all tests

npx playwright test

Run a specific file

npx playwright test tests/login.spec.ts

Run headed

npx playwright test –headed

Run a specific browser project

npx playwright test –project=chromium

Debug

npx playwright test –debug

Open HTML report

npx playwright show-report

Interview Tip

Know the difference between test execution, debug execution, and report viewing commands.


3. Playwright Locator Cheat Sheet

Locators are among the most important topics in a Playwright interview cheat sheet because locator quality directly affects test reliability.

getByRole()

Best for accessible interactive elements.

await page.getByRole(‘button’, {

  name: ‘Login’

}).click();

Interview Tip: Prefer role-based locators when the accessible role and name are meaningful.


getByLabel()

Useful for form controls.

await page.getByLabel(‘Email’).fill(

  ‘user@example.com’

);

Interview Tip: This is generally preferable to selecting an input using a generated CSS class.


getByText()

Useful for visible text.

await page.getByText(‘Order successful’).click();

Interview Tip: Be careful when the same text appears in multiple locations.


getByPlaceholder()

await page

  .getByPlaceholder(‘Search products’)

  .fill(‘Laptop’);


getByTestId()

await page

  .getByTestId(‘checkout-button’)

  .click();

Interview Tip: Test IDs are useful when the application deliberately exposes stable testing contracts.


locator()

await page.locator(‘.product-card’).first().click();

Use CSS or other selectors when appropriate.


XPath

await page.locator(

  ‘//button[@data-action=”submit”]’

).click();

Interview Tip

Do not claim XPath is always bad. Explain that long, brittle XPath expressions based on DOM structure are difficult to maintain.


4. Locator Chaining and Filtering

Suppose multiple products have an Add to Cart button.

Instead of:

await page.getByRole(‘button’, {

  name: ‘Add to Cart’

}).nth(2).click();

Use:

const product = page

  .getByRole(‘article’)

  .filter({ hasText: ‘Laptop Pro’ });

await product.getByRole(‘button’, {

  name: ‘Add to Cart’

}).click();

Interview Tip

The best locator usually describes the business relationship between the elements.


5. Strict Mode Quick Reference

Playwright actions generally expect the locator to identify the intended element uniquely.

This can cause a strict-mode violation:

await page.getByRole(‘button’, {

  name: ‘Delete’

}).click();

if multiple Delete buttons exist.

Fix

Scope the locator:

const row = page

  .getByRole(‘row’)

  .filter({ hasText: ‘ORD-1001’ });

await row.getByRole(‘button’, {

  name: ‘Delete’

}).click();

Interview Answer

“I would first make the locator unique by using semantic information, filtering, or chaining. I would use nth() only when element position is actually part of the requirement.”


6. Actions Cheat Sheet

ActionExample
Navigatepage.goto(‘/login’)
Clicklocator.click()
Filllocator.fill(‘text’)
Typelocator.pressSequentially(‘text’)
Checklocator.check()
Unchecklocator.uncheck()
Selectlocator.selectOption(‘value’)
Hoverlocator.hover()
Focuslocator.focus()
Press keylocator.press(‘Enter’)
Uploadlocator.setInputFiles()
Screenshotpage.screenshot()

Example

await page.goto(‘/login’);

await page.getByLabel(‘Email’)

  .fill(‘qa@example.com’);

await page.getByLabel(‘Password’)

  .fill(‘secret’);

await page.getByRole(‘button’, {

  name: ‘Login’

}).click();


7. Assertions Cheat Sheet

Import:

import {

  test,

  expect

} from ‘@playwright/test’;

Visibility

await expect(locator)

  .toBeVisible();

Text

await expect(locator)

  .toHaveText(‘Success’);

URL

await expect(page)

  .toHaveURL(/dashboard/);

Title

await expect(page)

  .toHaveTitle(/Dashboard/);

Value

await expect(locator)

  .toHaveValue(‘John’);

Attribute

await expect(locator)

  .toHaveAttribute(‘type’, ‘submit’);

Interview Tip

Prefer web-first assertions over manual polling or arbitrary delays.


8. Browser, Context, and Page

Browser

Represents the browser process.

const browser = await chromium.launch();

BrowserContext

Represents an isolated session.

const context =

  await browser.newContext();

Page

Represents a tab.

const page =

  await context.newPage();

Multi-user example

const admin =

  await browser.newContext({

    storageState: ‘admin.json’

  });

const customer =

  await browser.newContext({

    storageState: ‘customer.json’

  });

Interview Question

Why use BrowserContext instead of launching a new browser for every test?

Short Answer: Contexts provide lightweight session isolation and make independent users and tests easier to manage.


9. Waits, Auto-Waiting, and Synchronization

One of the most important concepts in this Playwright interview cheat sheet is synchronization.

Avoid

await page.waitForTimeout(5000);

Prefer

await expect(

  page.getByRole(‘status’)

).toContainText(‘Completed’);

Why?

Fixed waits:

  • Slow down tests
  • Do not guarantee application readiness
  • Create unnecessary timing dependencies

Playwright automatically waits for relevant actionability conditions before performing many actions.

Interview Answer

“I synchronize against application state instead of using arbitrary time-based waits.”


10. Frames, Popups, Tabs, Uploads, and Downloads

Iframe

const frame =

  page.frameLocator(‘#payment-frame’);

await frame.getByLabel(‘Card Number’)

  .fill(‘4111111111111111’);

Popup

const popupPromise =

  page.waitForEvent(‘popup’);

await page.getByRole(‘link’, {

  name: ‘Open Report’

}).click();

const popup =

  await popupPromise;

Upload

await page.getByLabel(‘Resume’)

  .setInputFiles(

    ‘tests/data/resume.pdf’

  );

Download

const downloadPromise =

  page.waitForEvent(‘download’);

await page.getByRole(‘button’, {

  name: ‘Download’

}).click();

const download =

  await downloadPromise;

await download.saveAs(

  ‘downloads/report.pdf’

);

Interview Tip

For events such as popup and download, start listening before triggering the action.


11. POM, Fixtures, Hooks, and Configuration

Page Object Model

class LoginPage {

  constructor(private page: Page) {}

  async login(

    username: string,

    password: string

  ) {

    await this.page

      .getByLabel(‘Username’)

      .fill(username);

    await this.page

      .getByLabel(‘Password’)

      .fill(password);

    await this.page

      .getByRole(‘button’, {

        name: ‘Login’

      })

      .click();

  }

}

POM Interview Answer

“POM separates test intent from UI implementation and makes locator changes easier to maintain.”


Hooks

test.beforeEach(async ({ page }) => {

  await page.goto(‘/login’);

});

test.afterEach(async ({ page }) => {

  // cleanup

});

Fixtures

Fixtures provide reusable dependencies.

type Fixtures = {

  loginPage: LoginPage;

};

export const test =

  base.extend<Fixtures>({

    loginPage: async ({ page }, use) => {

      await use(

        new LoginPage(page)

      );

    }

  });

Interview Tip

For senior interviews, understand fixture scope, setup, teardown, and worker isolation.


12. Authentication and storageState

Save authentication

await page.context()

  .storageState({

    path: ‘playwright/.auth/user.json’

  });

Reuse authentication

use: {

  storageState:

    ‘playwright/.auth/user.json’

}

Why use it?

It avoids repeating expensive UI login steps.

Important Security Rule

Do not commit authentication state files containing sensitive cookies or tokens.

Senior Interview Question

How would you handle authentication in parallel execution?

Answer: If tests modify server-side state, use isolated accounts or worker-scoped authentication so parallel workers do not interfere with each other.


13. API Testing and Network Mocking

API request

test(‘create user’, async ({

  request

}) => {

  const response =

    await request.post(‘/api/users’, {

      data: {

        name: ‘John’

      }

    });

  expect(response.ok())

    .toBeTruthy();

});

API-driven test data

const response =

  await request.post(‘/api/orders’, {

    data: {

      productId: 100,

      quantity: 2

    }

  });

const order =

  await response.json();

Mock API

await page.route(

  ‘**/api/products’,

  async route => {

    await route.fulfill({

      status: 200,

      contentType:

        ‘application/json’,

      body: JSON.stringify({

        products: [

          {

            id: 1,

            name: ‘Laptop’

          }

        ]

      })

    });

  }

);

Interview Tip

Use API calls for efficient setup and mocks for deterministic UI scenarios. Do not replace every integration test with mocks.


14. Parallel Execution, Retries, and Sharding

Workers

npx playwright test –workers=4

Workers execute tests concurrently.

Important

More workers do not always mean faster execution.

Potential bottlenecks:

  • CPU
  • Memory
  • Database
  • API rate limits
  • Shared test data
  • Application capacity

Retries

Configuration:

retries: 2

Interview Answer

“Retries can reduce transient CI noise, but they should not be used to hide permanent test flakiness.”


Sharding

npx playwright test –shard=1/4

This runs one of four test shards.

Workers vs Sharding

FeatureWorkersSharding
ParallelismWithin a runAcross CI jobs
Typical useFaster local/CI executionLarge regression suites
InfrastructureSame jobMultiple jobs/machines

15. Screenshots, Videos, Traces, and Reporting

Screenshot

await page.screenshot({

  path: ‘screenshots/home.png’,

  fullPage: true

});

Trace

use: {

  trace: ‘retain-on-failure’

}

Screenshot on failure

use: {

  screenshot: ‘only-on-failure’

}

Video

use: {

  video: ‘retain-on-failure’

}

HTML Report

npx playwright show-report

Debugging Principle

When a test fails:

Error → Reproduce → Inspect Trace → Check Locator → Check Synchronization → Check Data → Check Environment → Fix Root Cause


16. CI/CD, GitHub Actions, and Docker

A typical Playwright CI pipeline contains:

Checkout

   ↓

Install Node

   ↓

npm ci

   ↓

Install Playwright browsers

   ↓

Set environment variables

   ↓

Run tests

   ↓

Upload reports

   ↓

Publish diagnostics

GitHub Actions Example

name: Playwright Tests

on:

  push:

    branches: [main]

  pull_request:

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      – uses: actions/checkout@v4

      – uses: actions/setup-node@v4

        with:

          node-version: 20

          cache: npm

      – 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/

Interview Tip

If tests fail only in CI, investigate:

  • Browser versions
  • Node version
  • Environment variables
  • Secrets
  • Authentication
  • Test data
  • Worker count
  • CPU/memory
  • Network
  • Fonts and OS differences

17. Common Playwright Errors and Quick Fixes

ErrorLikely CauseQuick Fix
Strict mode violationMultiple matching elementsNarrow locator
Timeout exceededElement/state never became readyInspect locator and application state
Element not foundWrong locator or page stateCheck URL, frame, locator
Element not clickableOverlay/actionability issueInspect trace
Detached from DOMUI re-renderUse locator rather than stale element assumptions
Test passes locally, fails CIEnvironment differenceCompare CI/local environments
Browser not installedMissing browser binariesnpx playwright install
Authentication failureInvalid state/sessionRecreate or inspect auth state
Parallel failuresShared test dataIsolate test data
Missing reportArtifact step skippedUpload with if: always()

Interview Tip

Avoid fixing every failure with:

await page.waitForTimeout(5000);

That often hides the real problem.


18. Top Playwright Interview Questions With Short Answers

1. What is Playwright?

A modern browser automation and testing framework supporting Chromium, Firefox, and WebKit.

2. What is BrowserContext?

An isolated browser session containing independent cookies and storage.

3. What is a Page?

A browser tab within a BrowserContext.

4. What is auto-waiting?

Playwright waits for relevant actionability conditions before actions.

5. What is strict mode?

Playwright requires a unique target for actions that operate on one element.

6. Why prefer getByRole()?

It generally reflects the accessible, user-facing structure of the application.

7. What is POM?

A design pattern that encapsulates UI behavior and locators.

8. What are fixtures?

Reusable test dependencies and setup/teardown mechanisms.

9. What is storageState?

A mechanism for saving and reusing browser authentication/session state.

10. What is Trace Viewer?

A diagnostic tool for inspecting detailed test execution.

11. What is sharding?

Splitting a test suite across multiple CI jobs.

12. How do you handle flaky tests?

Find and fix the root cause rather than relying only on retries.

13. How do you mock APIs?

Use route interception such as page.route().

14. How do you handle iframes?

Use frameLocator() or frame APIs.

15. How do you reduce test execution time?

Optimize setup, reuse safe authentication, parallelize, shard, improve test data creation, and remove redundant coverage.


19. Scenario-Based Interview Quick Reference

Scenario: Locator matches multiple elements

Answer: Scope the locator using parent-child relationships, filter(), or chaining.


Scenario: Test passes locally but fails in CI

Answer: Compare environment, browser version, authentication, data, resources, network, and configuration. Use traces and artifacts.


Scenario: Element is dynamically rendered

Answer: Use a locator and web-first assertion instead of capturing a stale element or adding a fixed delay.


Scenario: Tests fail in parallel

Answer: Investigate shared accounts, database records, files, and application state.


Scenario: API is slow

Answer: Decide whether the test should wait for a meaningful application state, mock the API for deterministic UI testing, or test the slow API separately.


Scenario: CSS selector changes frequently

Answer: Replace implementation-dependent selectors with role, label, test ID, or another stable contract.


Scenario: Login is slow

Answer: Consider authentication setup and storageState, provided the tests do not need to validate the login flow itself.


Scenario: Regression suite takes hours

Answer: Profile the suite, remove redundant tests, optimize setup, use workers, shard CI jobs, and improve data creation.


20. TypeScript Coding Snippets for Interviews

Basic Test

test(‘dashboard’, async ({ page }) => {

  await page.goto(‘/dashboard’);

  await expect(

    page.getByRole(‘heading’, {

      name: ‘Dashboard’

    })

  ).toBeVisible();

});

Dropdown

await page

  .getByLabel(‘Country’)

  .selectOption(‘India’);

Checkbox

await page

  .getByLabel(‘Accept terms’)

  .check();

Keyboard

await page

  .getByPlaceholder(‘Search’)

  .press(‘Enter’);

Dynamic table

const row = page

  .getByRole(‘row’)

  .filter({ hasText: ‘ORD-1001’ });

await expect(row)

  .toContainText(‘Completed’);

API validation

const response =

  await request.get(‘/api/users’);

expect(response.status())

  .toBe(200);

Coding Interview Tip

While coding, explain your decisions. Interviewers often evaluate your reasoning, not just whether the code runs.


21. Beginner-to-Senior Playwright Revision Checklist

Beginner

  • Playwright architecture
  • Installation
  • page.goto()
  • Basic locators
  • Actions
  • Assertions
  • Auto-waiting
  • Screenshots
  • Basic POM

2–3 Years

  • Advanced locators
  • Strict mode
  • Fixtures
  • Hooks
  • Authentication
  • storageState
  • API testing
  • Network mocking
  • Parallel workers
  • Trace Viewer

4–5 Years

  • Worker-scoped fixtures
  • Test-data isolation
  • Multi-role authentication
  • Sharding
  • Docker
  • CI/CD
  • Flaky-test analysis
  • Framework refactoring
  • Selenium migration

Senior SDET / QA Lead


22. FAQs About the Playwright Interview Cheat Sheet

What should I revise first before a Playwright interview?

Start with BrowserContext, Page, locators, assertions, auto-waiting, POM, fixtures, authentication, API testing, and debugging.

Is Playwright difficult to learn?

The basic APIs are relatively straightforward. The more challenging part is designing reliable, maintainable automation and understanding synchronization, isolation, test data, and CI/CD.

Which Playwright locator should I use?

Prefer a stable user-facing locator such as getByRole() or getByLabel() when appropriate. Use test IDs when the application provides an intentional test contract.

Should I use XPath in Playwright?

Yes, when it is genuinely appropriate. Avoid unnecessarily long XPath expressions that depend heavily on DOM structure.

Is waitForTimeout() recommended?

Generally, no. Prefer Playwright’s auto-waiting and web-first assertions.

What should experienced Playwright candidates know?

Experienced candidates should understand fixtures, authentication, API testing, mocking, test-data isolation, parallelism, sharding, CI/CD, Docker, debugging, and framework architecture.

What should a Senior SDET know?

A Senior SDET should be able to design a scalable framework, isolate tests, optimize CI execution, manage authentication and data, debug production-like failures, and explain engineering trade-offs.

Can this Playwright interview cheat sheet be used for last-minute revision?

Yes. Focus on the tables, commands, short interview answers, scenarios, and TypeScript snippets during the final revision.

Leave a Comment

Your email address will not be published. Required fields are marked *