PART I — FOUNDATIONS
Section 1: Playwright Fundamentals
What is Software Testing?
Software testing is the process of evaluating a software application to verify that it functions according to its requirements. It helps identify bugs, missing features, and performance bottlenecks before the software reaches the end-user.
Manual vs Automation Testing
| Feature | Manual Testing | Automation Testing |
|---|---|---|
| Definition | Testing software manually by a human without scripts. | Using testing tools/scripts to execute tests automatically. |
| Execution Time | Time-consuming and slow. | Fast and highly scalable. |
| Accuracy | Prone to human error, especially in repetitive tasks. | Highly accurate; scripts do exactly what they are programmed to do. |
| Cost | High initial manual labor cost, lower setup cost. | High initial setup cost, but lower cost over time. |
| Best For | Exploratory, Usability, and Ad-hoc testing. | Regression, Load, Performance, and Repeated Execution testing. |
What is Test Automation?
Test automation is the use of specialized software to control the execution of tests and compare actual outcomes with predicted outcomes. It automates highly repetitive testing tasks previously performed manually, providing faster feedback loops for developers.
What is End-to-End (E2E) Testing?
End-to-End (E2E) testing validates the entire software application from start to finish, exactly as a real user would experience it. It ensures that all integrated components (UI, database, network, backend services) work together correctly in a production-like scenario.
What is Playwright?
What is it? Playwright is an open-source, modern automation framework developed by Microsoft designed for end-to-end testing of web applications. Why do we need it? Modern web applications are complex (SPAs, dynamic content, Shadow DOM). Traditional tools like Selenium struggle with flakiness and synchronization issues. Playwright was built from the ground up to handle the modern web reliably. How does it work? It interacts directly with the browser's underlying engine via the Chrome DevTools Protocol (CDP) for Chromium, and similar protocols for Firefox and WebKit, allowing bidirectional communication and granular control.
Why Playwright? (Problems it Solves)
- Flakiness: Built-in auto-waiting ensures elements are ready before interacting.
- Speed: Out-of-process architecture makes it incredibly fast.
- Cross-Browser: Tests all modern rendering engines (Chromium, WebKit, Firefox) with a single API.
- Context Isolation: Browser contexts provide fast, isolated test environments without the overhead of restarting the browser.
Playwright vs Selenium
| Feature | Playwright | Selenium |
|---|---|---|
| Architecture | Direct communication via CDP/browser protocols (Bidirectional). | Communicates via WebDriver HTTP API (Request/Response). |
| Browsers | Chromium, WebKit, Firefox (Bundled engines). | Chrome, Safari, Firefox, Edge, IE. |
| Speed | Extremely fast due to direct protocol communication. | Slower due to WebDriver HTTP overhead. |
| Auto-Waiting | Native, built-in auto-waiting for elements/network. | Requires explicit/implicit waits (WebDriverWait). |
| Parallelism | Native support via multiple workers and browser contexts. | Requires Selenium Grid or TestNG/JUnit configurations. |
| Language Support | TS/JS, Python, Java, .NET. | Java, Python, C#, Ruby, JS. |
| API Testing | Built-in API testing capabilities. | Not natively supported (requires external libraries). |
| Debugging | Playwright Inspector, Trace Viewer, UI Mode. | Standard IDE debugging. |
| Mobile | Emulates mobile views and supports Android testing natively. | Requires Appium for mobile automation. |
| Maturity | Newer (released 2020), rapidly growing. | Very mature, massive legacy codebase support. |
| Use Case | Modern SPAs, fast CI/CD pipelines, multi-tab testing. | Legacy systems, widespread grid requirements, specific obscure browsers. |
Playwright vs Cypress
| Feature | Playwright | Cypress |
|---|---|---|
| Architecture | Out-of-process (runs outside the browser via CDP). | In-browser (runs inside the browser with the application code). |
| Browser Control | Full control over the browser (multiple tabs, windows). | Limited to a single tab/window. |
| Multi-Domain | Fully supports testing across multiple origins easily. | Historically struggled with multi-origin (though improved recently). |
| Parallelism | Built-in parallelism locally and in CI. | Parallelism requires paid Cypress Cloud or complex workarounds. |
| Language Support | TS/JS, Python, Java, .NET. | JavaScript/TypeScript only. |
| Selectors | Text, CSS, XPath, React selectors, Shadow DOM native. | CSS primarily, XPath requires plugins. |
| Network Mocking | Intercepts at the browser level natively. | Powerful built-in network stubbing/mocking. |
| Ecosystem | Rapidly growing Microsoft backed. | Huge community, massive plugin ecosystem. |
When to use each tool:
- Playwright: Choose when testing modern web apps across multiple browsers, handling multiple tabs/iframes, requiring deep network interception, or when you need fast, parallel execution locally.
- Selenium: Choose when you need to test legacy browsers (IE11), have an existing massive Selenium codebase, or need to run on a vast legacy device grid.
- Cypress: Choose for component testing, frontend developer-driven testing, or if the team exclusively uses JavaScript and prefers the interactive Cypress test runner.
Playwright Architecture
Playwright operates completely out-of-process. Instead of sending HTTP requests to a driver (like Selenium), Playwright opens a WebSocket connection to the browser.
- Node.js/Test Process: Runs your test script.
- WebSocket Connection: Communicates over CDP (Chrome DevTools Protocol).
- Browser Process: Executes commands instantly. Because it's a persistent WebSocket connection, Playwright can listen to browser events (like network requests, console logs, dialogs) in real-time, enabling its signature auto-waiting and intercept features.
Supported Browsers
Playwright downloads its own custom browser binaries to guarantee compatibility:
- Chromium: Engine for Google Chrome, Microsoft Edge, Opera.
- Firefox: Engine for Mozilla Firefox.
- WebKit: Engine for Apple Safari.
Headless vs Headed Mode
- Headless Mode (
--headless): The browser runs in the background without a graphical user interface (GUI).- Why/When: Faster execution, less resource-intensive. Used for CI/CD pipelines and background test runs.
- Headed Mode (
--headed): The browser opens with a visible GUI.- Why/When: Used for debugging, writing tests, and visually watching test execution.
Browser Automation Basics
- Browser: A single instance of a browser engine (e.g., Chromium). Launching a browser is expensive.
- Browser Context: An isolated incognito-like session within a browser. Fast to create and destroy. Contexts do not share cookies or local storage.
- Page: A single tab or popup within a Browser Context. Tests interact primarily with the Page.
Playwright Test vs Playwright Library
- Playwright Library (
playwright): Just the automation API. You bring your own test runner (Jest, Mocha) and assertion library. - Playwright Test (
@playwright/test): The fully integrated testing framework. Includes the automation API plus a test runner, assertions (expect), fixtures, parallelization, and reporting. Always use this for QA automation.
Advantages of Playwright
- Built-in auto-waiting.
- Cross-browser support (Chromium, Firefox, WebKit).
- Multi-tab, multi-origin, and iframe support.
- Powerful built-in assertions.
- In-built Trace Viewer and UI Mode for unparalleled debugging.
- Network interception and API testing out-of-the-box.
- Seamless handling of Shadow DOM.
- Codegen for rapid script creation.
- Native parallel execution.
- Multi-language support.
Limitations of Playwright
- No support for legacy browsers like Internet Explorer 11.
- Real mobile device testing is limited (uses emulation for mobile browsers; true native app testing requires Appium/Detox).
- Steeper learning curve if transitioning from strictly WebDriver concepts.
When to use Playwright
For modern web applications, E2E testing, API testing, cross-browser validation, and when test execution speed and reliability are paramount.
When NOT to use Playwright
When testing legacy enterprise apps strictly requiring IE11, or when doing pure native mobile app testing (iOS/Android applications).
Interview Explanation for 'What is Playwright?'
"Playwright is a modern, open-source E2E testing framework backed by Microsoft. Unlike older tools like Selenium that use WebDriver HTTP requests, Playwright communicates directly with the browser via protocols like CDP over a WebSocket. This architecture allows it to execute faster, listen to real-time browser events, and provide built-in auto-waiting, which massively reduces test flakiness. It supports all major browser engines, handles multi-tab scenarios flawlessly, and comes with a dedicated test runner."
Common Interview Questions
- What is the difference between Playwright and Selenium?
- Explain the architecture of Playwright.
- How does Playwright handle synchronization and wait times?
- What is a Browser Context in Playwright?
- Can you test APIs using Playwright?
- How does Playwright handle multiple tabs and windows?
- What are the supported browsers in Playwright?
- Explain the difference between Playwright Library and Playwright Test.
- How does Playwright deal with Shadow DOM?
- What is headless mode and when do you use it?
Section 2: JavaScript/TypeScript Essentials for Playwright
async/await
What is it? Playwright APIs are entirely asynchronous. async/await is syntactic sugar over Promises that makes asynchronous code look synchronous.
Example:
test('async/await example', async ({ page }) => {
// await ensures the script waits for the action to complete
await page.goto('https://example.com');
await page.click('button#submit');
});Promise
What is it? A Promise represents the eventual completion (or failure) of an asynchronous operation. await resolves a Promise. If you forget await, Playwright returns a pending Promise instead of performing the action, leading to flaky tests.
try/catch
What is it? Used for error handling. Crucial for soft assertions or custom error logging in tests. Example:
try {
await page.click('#fragile-button', { timeout: 2000 });
} catch (error) {
console.log('Button not found, continuing test...');
}Functions and Arrow Functions
Example:
// Standard function
function getUrl() { return 'https://example.com'; }
// Arrow function (used everywhere in Playwright)
const clickLogin = async (page: Page) => {
await page.click('#login');
};Classes, Constructors, Inheritance
Why? Essential for the Page Object Model (POM) design pattern. Example:
export class LoginPage {
readonly page: Page;
constructor(page: Page) {
this.page = page; // Constructor initializes the page instance
}
async login(user: string, pass: string) {
await this.page.fill('#username', user);
await this.page.fill('#password', pass);
}
}Interfaces and Types (TypeScript)
Why? For strict typing of test data and API responses. Example:
interface UserData {
username: string;
role: 'admin' | 'guest';
}
const user: UserData = { username: 'testuser', role: 'admin' };Modules: import/export
Why? To organize code, fixtures, and page objects across multiple files. Example:
// utils.ts
export const BASE_URL = 'https://app.com';
// test.spec.ts
import { BASE_URL } from './utils';Destructuring
Why? Used in every Playwright test to extract page, browser, or custom fixtures from the test arguments.
Example:
// Object destructuring extracts 'page' from the arguments object
test('destructuring', async ({ page, context, request }) => {
await page.goto('/');
});Arrays: map, filter
Why? Useful for data-driven testing and working with multiple elements. Example:
const roles = ['admin', 'editor', 'viewer'];
// Data-driven test using map
for (const role of roles) {
test(`Test login for ${role}`, async ({ page }) => {
await loginAs(page, role);
});
}Environment Variables (process.env)
Why? To hide secrets and switch environments (dev/qa/staging). Example:
// Running: PASSWORD=secret npx playwright test
test('env vars', async ({ page }) => {
await page.fill('#pwd', process.env.PASSWORD as string);
});Template Literals
Why? String interpolation for dynamic selectors. Example:
const rowId = 5;
// Uses backticks (`) and ${}
await page.locator(`tr#row-${rowId} >> button.delete`).click();Section 3: Installation and Project Setup
Node.js Requirements and npm basics
Playwright is a Node.js library. You must have Node.js installed (v16+ recommended).
npm(Node Package Manager) is used to install libraries.package.jsonkeeps track of installed libraries and custom scripts.
Installing Playwright Step by Step
Open a terminal and run the official initialization command:
npm init playwright@latestWhat it does: This CLI wizard scaffolds a complete Playwright project. It asks:
- TypeScript or JavaScript? (Choose TypeScript)
- Location of tests? (Default:
tests) - Add a GitHub Actions workflow? (Y/n)
- Install Playwright browsers? (Y/n - Choose Y)
If you didn't install browsers during setup, you run:
npx playwright installComplete Project Folder Structure
my-playwright-project/
├── .github/workflows/playwright.yml # CI/CD configuration for GitHub Actions
├── node_modules/ # Installed npm packages (never commit this)
├── tests/ # Your test files live here
│ └── example.spec.ts # Sample test generated by Playwright
├── tests-examples/ # Extended examples provided by Playwright
├── .gitignore # Tells Git which files to ignore
├── package.json # Project metadata and dependencies
├── package-lock.json # Exact dependency versions
└── playwright.config.ts # Global configuration for PlaywrightExplain Every Generated File
playwright.config.ts: The heart of Playwright. Defines test directories, timeouts, retries, reporters, and multi-browserprojects.package.json: Contains the@playwright/testdependency. You can add scripts here like"test": "playwright test".tests/example.spec.ts: The entry point. A ready-to-run test demonstrating basic syntax.
First Test Walkthrough (Line-by-Line)
// 1. Import 'test' (the runner) and 'expect' (assertion library) from Playwright
import { test, expect } from '@playwright/test';
// 2. Define a test block with a title.
// 3. Destructure '{ page }' from the test context (the isolated browser tab).
test('has title', async ({ page }) => {
// 4. Navigate to the URL. 'await' pauses execution until navigation completes.
await page.goto('https://playwright.dev/');
// 5. Use the 'expect' assertion. Playwright automatically waits for the title to match.
await expect(page).toHaveTitle(/Playwright/);
});Running the First Test
Run the test in headless mode (default):
npx playwright testTo see the browser physically open, run it headed:
npx playwright test --headedInterview Questions on Setup
- What command is used to initialize a new Playwright project?
- What is the purpose of the
playwright.config.tsfile? - How do you install the browser binaries required by Playwright?
- What is the difference between
npmandnpxin the context of Playwright? - Why is TypeScript preferred over JavaScript for Playwright?
Section 4: CLI Commands
Playwright comes with a powerful Command Line Interface (CLI). Using npx playwright <command> ensures you are using the local installation of Playwright.
Core Commands Detailed
-
npx playwright testRuns all tests in the project in headless mode across all configured browsers. -
npx playwright test tests/example.spec.tsRuns a specific test file instead of the whole suite. Great for isolated debugging. -
npx playwright test --headedRuns tests visually, showing the browser UI. Essential for local development. -
npx playwright test --debugOpens the Playwright Inspector. It pauses test execution on the first line and allows you to step through the code, inspect the DOM, and see live selector resolution. -
npx playwright test --uiOpens the revolutionary Playwright UI Mode. It provides a visual time-travel trace of your test, showing the DOM, network requests, console logs, and source code side-by-side. -
npx playwright test --project=chromiumRuns tests only on the specified project (as defined inplaywright.config.ts). Saves time when you don't need to test WebKit/Firefox locally. -
npx playwright test --workers=1Forces Playwright to run tests sequentially (one worker) instead of in parallel. Useful for debugging tests that fail due to shared state or resource contention. -
npx playwright test --grep 'login'Runs only tests whose titles match the regex/string 'login'. -
npx playwright test --grep-invert 'slow'Runs all tests EXCEPT those matching the string 'slow'. -
npx playwright test --reporter=htmlOverrides the configured reporter to generate an HTML report. -
npx playwright test --retries=2Forces failing tests to retry up to 2 times. Useful for assessing flakiness. -
npx playwright test --repeat-each=3Runs every test 3 times. Excellent for identifying flaky tests. -
npx playwright test --timeout=60000Overrides the global test timeout to 60 seconds (60,000ms). -
npx playwright show-reportStarts a local web server to serve the HTML test report generated after a test run. -
npx playwright codegenOpens a browser and the Playwright Inspector side-by-side. As you click through the browser, it generates Playwright script code automatically. -
npx playwright codegen https://example.comStarts Codegen directly at the specified URL. -
npx playwright installDownloads the necessary browser binaries (Chromium, Firefox, WebKit) required by your current Playwright version. -
npx playwright install chromiumInstalls only the Chromium binary, saving disk space and time if you don't need the others. -
npx playwright test --listLists all tests that would be executed without actually running them. -
npx playwright test --update-snapshotsUpdates the reference images for visual regression testing (screenshots).
CLI Cheat Sheet Table
| Command | Purpose |
|---|---|
npx playwright test | Run all tests |
npx playwright test --ui | Run tests in interactive UI mode |
npx playwright test --headed | Run tests visibly |
npx playwright test --debug | Run tests step-by-step in Inspector |
npx playwright codegen | Record actions and generate code |
npx playwright show-report | View HTML test report |
npx playwright install | Download browser binaries |
Common Mistakes:
- Forgetting
npx: Runningplaywright testinstead ofnpx playwright testwill result in a "command not found" error if Playwright isn't installed globally (which it shouldn't be). - Leaving
--headedin CI: Ensure CI commands use standard headless execution to save resources.
PART II — CORE CONCEPTS
Section 5: Playwright Architecture Deep Dive
What is it?
Playwright's architecture is a hierarchical structure that manages browser automation. It operates out-of-process via WebSocket connections, allowing for fast, reliable, and isolated testing. The core hierarchy consists of Browser, BrowserContext, Page, Locator, and elements.
Why do we need it?
A structured architecture allows Playwright to:
- Guarantee complete test isolation (using Contexts).
- Optimize resource usage (launching one Browser, but multiple lightweight Contexts).
- Handle complex scenarios (multiple tabs, multiple domains, popup windows) effortlessly.
How it works
Playwright communicates with the browser using the Chrome DevTools Protocol (CDP) for Chromium-based browsers, and similar protocols for WebKit and Firefox. This out-of-process execution prevents issues like memory leaks or hanging tests from crashing the runner.
The Hierarchy Diagram
+-----------------------------------------------------------+
| Playwright |
+-----------------------------------------------------------+
|
v
+-----------------------------------------------------------+
| Browser (e.g., Chromium) |
| (Heavyweight process, launched once per worker) |
+-----------------------------------------------------------+
|
+-----------------------+-----------------------+
| |
v v
+-----------------------------+ +-----------------------------+
| BrowserContext 1 | | BrowserContext 2 |
| (Incognito-like profile: | | (Isolated: distinct cookies,|
| Cookies, Storage, Cache) | | localStorage, sessions) |
+-----------------------------+ +-----------------------------+
| |
+---+---+ +---+---+
| | | |
v v v v
+----+ +----+ +----+ +----+
|Page| |Page| (Tabs/Windows) |Page| |Page|
+----+ +----+ +----+ +----+
|
v
+-------+
|Locator| (Strict, lazy-evaluated blueprint to find elements)
+-------+
|
v
+-------+
|Element| (Actual DOM node)
+-------+
Core Components Explained
1. Browser
The physical browser instance (Chromium, Firefox, or WebKit). Launching a browser is expensive in terms of time and memory. Therefore, Playwright typically launches it once per worker process and reuses it for multiple tests.
2. BrowserContext
A BrowserContext is an isolated incognito-like session within a Browser. It is fast and cheap to create.
- Isolation: It encapsulates cookies, local storage, session storage, and cache. Tests run in separate contexts cannot interfere with each other.
- Permissions: Geolocation, camera access, and notification permissions are set at the context level.
Analogy: Imagine opening Google Chrome. The application itself is the Browser. When you press Ctrl+Shift+N, you open an Incognito window. This window is a BrowserContext. No matter what you log into there, it doesn't affect your main window or other incognito windows.
3. Page
A Page represents a single tab or popup window within a BrowserContext. This is where you navigate to URLs and interact with web applications. It emits events (like load, request, dialog) and handles routing.
4. Locator
A Locator is a recipe or blueprint for finding an element on a page. It is lazy (only evaluates when an action is performed) and auto-retrying (waits for the element to become visible, enabled, and stable before interacting).
Locator vs ElementHandle (Important Interview Topic)
| Feature | Locator (page.locator()) | ElementHandle (page.$()) |
|---|---|---|
| Concept | A blueprint/query to find an element. | A pointer to a specific DOM node. |
| Evaluation | Lazy. Evaluated just-in-time when an action occurs. | Immediate. Finds the element at that exact moment. |
| Auto-Waiting | Yes. Built-in strictness and waitability. | No. If the element isn't there yet, it returns null. |
| Stale Elements | Immune. Automatically re-evaluates the query if the DOM changes. | Vulnerable. Throws StaleElementReferenceError if the DOM updates. |
| Recommendation | Preferred. Always use Locators. | Legacy. Avoid unless strictly necessary (e.g., passing DOM nodes to page.evaluate). |
Syntax & Real-World Example
import { test, expect, chromium } from '@playwright/test';
test('Manual architecture demonstration', async () => {
// 1. Launch Browser
const browser = await chromium.launch({ headless: true });
// 2. Create an isolated Context
const context = await browser.newContext({
viewport: { width: 1280, height: 720 },
permissions: ['geolocation']
});
// 3. Create a Page (Tab) within the context
const page = await context.newPage();
// 4. Navigate
await page.goto('https://example.com');
// 5. Create a Locator
const headingLocator = page.getByRole('heading', { name: 'Example Domain' });
// 6. Action / Assertion (Locator is evaluated here)
await expect(headingLocator).toBeVisible();
// 7. Cleanup
await context.close();
await browser.close();
});Note: In normal @playwright/test usage, the test runner automatically provides isolated page and context fixtures, so you don't need to manually launch browsers.
test('Automatic architecture via fixtures', async ({ page, context }) => {
// The runner already created the Browser, Context, and Page!
await page.goto('https://example.com');
});Interview Explanation for Browser vs Context vs Page
"A Browser is the heavy underlying executable, like Chrome. Since starting it is slow, Playwright starts it once. A Context is a lightweight, isolated incognito profile inside that browser, holding its own cookies and cache. A Page is simply a single tab within that Context where the actual website loads. This design allows us to run hundreds of tests quickly and in perfect isolation by creating new Contexts rather than restarting the Browser."
Common Mistakes
- Restarting the Browser per test: Manually doing
chromium.launch()in every test instead of using thecontextorpagefixtures. It severely impacts performance. - Using
ElementHandle: Usingpage.$('#id')instead ofpage.locator('#id'), leading to flaky tests due to missing auto-wait and stale element errors. - Leaking state: Running multiple tests in a single page sequentially instead of using isolated contexts per test.
Best Practices
- Always use Locators.
- Rely on Test Fixtures: Use the
{ page }and{ context }fixtures provided by the test runner. - Test in Isolation: Let the runner create a new context per test to avoid state leakage (e.g., test A logs in and test B assumes it is logged out, but it's not).
Common Interview Questions
- How does Playwright ensure test isolation? (Contexts)
- What is the difference between a BrowserContext and a Page?
- Explain the difference between Locator and ElementHandle.
- Why did Playwright introduce Locators?
- How would you test a chat application where User A sends a message to User B in a single test? (Create two separate BrowserContexts in the test).
- Does Playwright run tests in the same browser window? (No, isolated contexts).
- What happens if a DOM element re-renders before a Playwright click action completes? (Locators handle it gracefully; ElementHandles throw stale reference).
- How do you share a login state across multiple tests to save time? (Global setup saving state to a file, then passing
storageStateto new Contexts). - What communication protocol does Playwright use? (CDP / WebSocket).
- Can you have multiple pages in one context? Yes, typically for testing
target="_blank"links or popups.
Section 6: Locators (COMPREHENSIVE)
What is a locator?
A locator is a smart blueprint that tells Playwright how to find a specific element on the page.
Why locators? (vs direct element access)
Direct access (like document.querySelector or Selenium's traditional findElement) executes instantly. If the element isn't there yet (due to network delays or animations), the test fails. Locators are lazy. They don't do anything until you call an action (like .click()). When you do, Playwright uses the locator's blueprint to poll the DOM, waiting for the element to appear, become visible, stop moving, and become interactive.
Locator Priority / Preference Order
Playwright strongly recommends user-facing locators. The priority order is:
- User-Facing:
getByRole(Best for accessibility and exactly how users see the page). - User-Facing:
getByText,getByLabel,getByPlaceholder,getByAltText,getByTitle. - Robust Engineering:
getByTestId(For dynamic content that has no good user-facing identifier). - Implementation Details (Avoid):
page.locator()with CSS or XPath (Brittle, breaks if DOM structure changes).
Locator Types Deep Dive
1. page.getByRole()
What: Finds elements by their ARIA role, aria-attributes, and accessible name.
Syntax: page.getByRole(role, { name?: string | RegExp, exact?: boolean, checked?: boolean, ... })
When to use: Your first choice for interactive elements (buttons, links, inputs).
// Simple Example
await page.getByRole('button', { name: 'Submit' }).click();
await page.getByRole('heading', { name: 'Welcome', exact: true }).toBeVisible();
await page.getByRole('checkbox', { name: 'Subscribe', checked: true }).click();2. page.getByText()
What: Finds elements by their text content.
Syntax: page.getByText(text, { exact?: boolean })
When to use: For non-interactive text elements (paragraphs, spans) where a role isn't appropriate.
// Partial match (matches "Hello World")
await expect(page.getByText('Hello')).toBeVisible();
// Exact match
await expect(page.getByText('Hello', { exact: true })).toBeVisible();3. page.getByLabel()
What: Finds form fields via their associated <label>.
Syntax: page.getByLabel(text, { exact?: boolean })
When to use: Input fields, dropdowns, and textareas.
// <label>Password</label><input type="password" />
await page.getByLabel('Password').fill('secret123');4. page.getByPlaceholder()
What: Finds inputs by their placeholder attribute. When to use: When inputs lack labels (though accessibility-wise, they should have labels).
await page.getByPlaceholder('Search for products...').fill('Laptop');5. page.getByAltText()
What: Finds images by their alt attribute.
When to use: Verifying images are rendered correctly.
await expect(page.getByAltText('Company Logo')).toBeVisible();6. page.getByTitle()
What: Finds elements by their title attribute.
When to use: Rarely, usually for tooltips or SVG titles.
await page.getByTitle('Close window').click();7. page.getByTestId()
What: Finds elements based on a custom data attribute (default is data-testid).
When to use: When elements lack reliable text or roles, and CSS changes frequently. Highly resilient.
// <div data-testid="cart-total">$45.00</div>
await expect(page.getByTestId('cart-total')).toHaveText('$45.00');
// Changing the default attribute in playwright.config.ts:
// use: { testIdAttribute: 'data-cy' }8. page.locator() (CSS & XPath)
What: Standard DOM selectors. When to use: Only when user-facing locators or test IDs are unavailable.
// CSS
await page.locator('.submit-btn').click();
await page.locator('article p:has-text("Playwright")').toBeVisible();
// XPath
await page.locator('//button[text()="Submit"]').click();Locator Filtering and Chaining
You can narrow down broad locators to target specific elements.
// Chaining (finding an element inside another)
const productCard = page.getByTestId('product-card');
await productCard.getByRole('button', { name: 'Add to Cart' }).click();
// Filtering
const rows = page.getByRole('row');
const myRow = rows.filter({ hasText: 'John Doe' });
const rowWithDelete = rows.filter({ has: page.getByRole('button', { name: 'Delete' }) });
await myRow.getByRole('button', { name: 'Edit' }).click();Handling Multiple Elements: nth(), first(), last()
If a locator resolves to multiple elements, actions like .click() will throw a strict mode error.
const buttons = page.getByRole('button');
await buttons.first().click(); // First button
await buttons.last().click(); // Last button
await buttons.nth(1).click(); // Second button (0-indexed)Best Practice: Avoid these if possible. If an element is the "second" one today, it might be the third one tomorrow. Filter by text or other identifiers instead.
Locator Strictness
By default, Playwright locators are strict. If a locator points to multiple elements and you try to act on it, Playwright throws an error instead of silently clicking the first one (like older tools did). This prevents tests from accidentally interacting with the wrong element.
Comparing Approaches
// 1. page.locator('#login')
// Brittle. What if the ID changes to 'login-btn'? Doesn't tell us what the element is.
// 2. page.locator('.login-button')
// Very brittle. Classes are for styling, and developers change them often (e.g., Tailwind).
// 3. page.getByRole('button', { name: 'Login' })
// EXCELLENT. This is exactly how a user (and a screen reader) finds the button. Resilient to DOM structure changes.
// 4. page.getByTestId('login-button')
// GOOD. Resilient to styling and DOM changes, but doesn't test accessibility.Common Mistakes
- Overusing CSS/XPath: Tying tests to
div > span > .activeleads to flaky tests when UI developers reorganize the DOM. - Ignoring Strict Mode Errors: Using
.first()to bypass strict mode errors instead of writing a better, more unique locator.
Best Practices
- Prefer
getByRole. It forces you to write accessible applications. - Store locators as variables in Page Object Models for reusability.
Common Interview Questions
- What is the difference between a locator and an element handle?
- Why does Playwright recommend user-facing locators over CSS/XPath?
- What is "Strict Mode" in Playwright?
- How do you find a specific row in a table that contains the text "Pending"? (Use
.filter({ hasText: 'Pending' })). - How would you click the 3rd button on a page? (using
.nth(2)). - Explain chaining locators.
- If
getByRole('button')returns 5 buttons, what happens when you doawait page.getByRole('button').click()? (Strict mode error). - How do you change the default attribute used by
getByTestId? - When should you use
getByTestIdvsgetByRole? - How does auto-waiting relate to locators?
- Can a locator be reused across multiple actions? (Yes, it re-evaluates the query each time).
- What does
getByPlaceholderdo? - Write a locator to find a label "Email" that is exact.
- How do you find an element that does NOT contain specific text? (
.filter({ hasNotText: '...' })). - Why is
.first()considered a bad practice?
Section 7: Actions and Interactions
What are actions?
Actions are how Playwright simulates user input (clicking, typing, dragging) on the locators you define.
Why do we need them?
To navigate flows, fill out forms, and trigger application state changes to test business logic.
How it works (Auto-Waiting)
Before performing an action, Playwright auto-waits for the element to pass actionability checks. For a click, it waits for the element to be:
- Attached to the DOM
- Visible
- Stable (not animating)
- Receives Events (not obscured by another element like a modal overlay)
- Enabled (not
disabled)
Core Actions
1. click()
What: Simulates a mouse click.
Options: button: 'right' | 'left' | 'middle', clickCount, force (bypasses actionability checks), position (x,y offset).
await page.getByRole('button', { name: 'Submit' }).click();
await page.getByRole('button').click({ clickCount: 2 }); // Double click
await page.getByRole('button').click({ force: true }); // Click even if covered2. dblclick()
What: Convenience method for double-clicking.
await page.getByTestId('folder').dblclick();3. fill() vs type() vs press() (Important Distinction)
fill()(Recommended): Clears the input and sets the value instantly. Fast and reliable. Emits input events.pressSequentially()(formerlytype()): Simulates pressing the keyboard keys one by one. Slower, but necessary for testing auto-complete or typeahead dropdowns.press(): Presses a single key or key combination (e.g., 'Enter', 'Control+A').
// standard form filling
await page.getByLabel('Username').fill('john_doe');
// testing a search box that fetches suggestions on keystroke
await page.getByPlaceholder('Search').pressSequentially('lap', { delay: 100 });
// submitting a form
await page.getByLabel('Password').press('Enter');4. clear()
What: Clears an input field.
await page.getByLabel('Comment').clear();5. check() and uncheck()
What: Interacts with checkboxes and radio buttons. Playwright ensures the state is correct before clicking.
await page.getByLabel('I agree to the terms').check();
await page.getByLabel('Subscribe to newsletter').uncheck();6. selectOption()
What: Selects options in <select> dropdowns.
const dropdown = page.getByLabel('Country');
await dropdown.selectOption('US'); // By value attribute
await dropdown.selectOption({ label: 'United States' }); // By visible text
await dropdown.selectOption({ index: 2 }); // By index7. setInputFiles()
What: Uploads files to an <input type="file">.
await page.getByLabel('Upload Resume').setInputFiles('path/to/resume.pdf');
// Multiple files
await page.getByLabel('Images').setInputFiles(['img1.png', 'img2.png']);8. hover()
What: Simulates mouse hover.
await page.getByRole('menuitem', { name: 'Profile' }).hover();9. focus()
What: Sets DOM focus on the element.
await page.getByLabel('Username').focus();10. dragAndDrop()
What: Drags an element to a target.
await page.getByTestId('item-1').dragAndDrop(page.getByTestId('dropzone'));11. Low-level Keyboard & Mouse APIs
Used for complex scenarios like drawing on a canvas or complex keyboard shortcuts.
// Keyboard
await page.keyboard.press('Control+KeyC');
await page.keyboard.insertText('Paste this'); // Instantly inserts text
// Mouse
await page.mouse.move(100, 200);
await page.mouse.down();
await page.mouse.move(200, 300);
await page.mouse.up();Real-World Example: Registration Form
test('User can register', async ({ page }) => {
await page.goto('https://example.com/register');
await page.getByLabel('First Name').fill('Alice');
await page.getByLabel('Last Name').fill('Smith');
await page.getByLabel('Country').selectOption({ label: 'Canada' });
await page.getByLabel('I accept the terms').check();
// Hover over tool-tip
await page.getByTestId('password-info').hover();
await page.getByLabel('Password').fill('SecurePassword123!');
await page.getByRole('button', { name: 'Sign Up' }).click();
});Common Mistakes
- Using
fillwhenpressSequentiallyis needed: If an input requires real keystrokes to trigger a dropdown,fillwon't work because it sets the value instantly. - Not awaiting actions: Forgetting the
awaitkeyword leads to unresolved promises and erratic behavior. - Using
force: truetoo often: If you have to force a click, it means a real user probably couldn't click it either. Investigate why it's obscured rather than forcing it.
Best Practices
- Rely on auto-waiting: Don't add arbitrary
page.waitForTimeout(1000). Let Playwright wait for actionability. - Use
fillby default: It's much faster than simulating individual keystrokes.
Common Interview Questions
- Explain the actionability checks Playwright performs before a click.
- What is the difference between
fill()andpressSequentially()(ortype())? - How do you bypass actionability checks? (Using
{ force: true }). - How do you upload a file? (
setInputFiles). - How would you test a drag and drop interface?
- How do you select multiple options in a multi-select dropdown? (Pass an array to
selectOption). - What happens if you try to
.click()an element that is behind a modal dialog? (Playwright waits for it to become unobscured. If it times out, it throws an error). - How do you simulate pressing the "Enter" key?
- How can you click at specific coordinates within an element? (Using the
positionoption inclick()). - How do you simulate a right-click? (
click({ button: 'right' })).
Section 8: Assertions
What is an assertion?
An assertion is a validation step in your test. It verifies that the application is in the expected state (e.g., verifying a success message appears after login).
expect() function
Playwright uses the expect function from its built-in Web-First Assertions library (based on Jest/Expect).
Auto-retrying assertions vs Non-retrying assertions (IMPORTANT)
- Auto-retrying assertions: Used with Locators and Pages. They don't fail immediately. They poll the DOM until the condition is met or the timeout (default 5000ms) is reached. They always start with
expect(locator).to...orexpect(page).to.... - Non-retrying assertions: Used with static values (strings, numbers). They evaluate instantly. They start with
expect(value).to....
// Auto-retrying: Waits for the text to appear asynchronously.
await expect(page.getByTestId('status')).toHaveText('Success');
// Non-retrying: Evaluates immediately.
expect(2 + 2).toBe(4);Locator Assertions (Auto-retrying)
Visibility & State
const btn = page.getByRole('button', { name: 'Submit' });
await expect(btn).toBeVisible(); // Is it on screen?
await expect(btn).toBeHidden(); // Is it gone/not displayed?
await expect(btn).toBeEnabled(); // Is it clickable?
await expect(btn).toBeDisabled(); // Is it disabled (e.g., loading state)?
await expect(btn).toBeAttached(); // Is it in the DOM (even if hidden)?Content
const alert = page.getByRole('alert');
// Exact text match
await expect(alert).toHaveText('Form submitted successfully!');
// Partial text match (Useful for dynamic IDs mixed with text)
await expect(alert).toContainText('submitted successfully');
// Value of an input field
await expect(page.getByLabel('Email')).toHaveValue('test@example.com');
// Checking if an element contains no text/nodes
await expect(page.locator('#error-container')).toBeEmpty();Attributes & Styling
const link = page.getByRole('link', { name: 'Dashboard' });
// Check HTML attributes
await expect(link).toHaveAttribute('href', '/dashboard');
// Check CSS classes
await expect(link).toHaveClass(/active/); // Regex is useful for multiple classes
// Check computed CSS styles
await expect(link).toHaveCSS('color', 'rgb(255, 0, 0)');Counts
// Verify exactly 5 list items exist
await expect(page.getByRole('listitem')).toHaveCount(5);Form Controls
await expect(page.getByLabel('Subscribe')).toBeChecked();
await expect(page.getByLabel('Username')).toBeFocused();
await expect(page.getByLabel('Comments')).toBeEditable();Page Assertions (Auto-retrying)
await expect(page).toHaveURL('https://example.com/dashboard');
await expect(page).toHaveURL(/.*dashboard/); // Using Regex
await expect(page).toHaveTitle('My App - Dashboard');Generic Assertions (Non-retrying)
Standard Jest-like matchers for testing data structures, API responses, or static logic.
expect(status).toBe(200); // Exact equality
expect(userData).toEqual({ name: 'John', age: 30 }); // Deep object equality
expect(isValid).toBeTruthy();
expect([1, 2, 3]).toContain(2);
expect(items).toHaveLength(3);
expect('playwright').toMatch(/play/);Negating Assertions
Add .not to reverse the logic.
await expect(page.getByText('Loading...')).not.toBeVisible();
expect(user.role).not.toBe('admin');Soft Assertions
What: expect.soft() allows a test to continue executing even if the assertion fails.
Why: To gather multiple assertion failures in a single test run without stopping at the first failure.
When: Validating a list of non-critical UI elements (e.g., checking if 5 different icons are visible).
test('Verify UI layout', async ({ page }) => {
// If the logo is missing, the test marks as failed but continues.
await expect.soft(page.getByAltText('Logo')).toBeVisible();
// If the nav is missing, it also marks failed and continues.
await expect.soft(page.getByRole('navigation')).toBeVisible();
// Standard assertion - if this fails, the test stops immediately.
await expect(page.getByRole('main')).toBeVisible();
});Polling Assertions: expect.poll()
Used when you need to repeatedly check a condition that isn't tied to the DOM (like checking a database or a downloaded file).
await expect.poll(async () => {
const response = await fetch('https://api.example.com/status');
const data = await response.json();
return data.status;
}, { timeout: 10000 }).toBe('ready');Real-World Assertion Examples
test('Login flow assertions', async ({ page }) => {
await page.goto('/login');
// Verify initial state
await expect(page).toHaveTitle('Login');
await expect(page.getByRole('button', { name: 'Login' })).toBeDisabled();
// Fill credentials
await page.getByLabel('Username').fill('user1');
await page.getByLabel('Password').fill('pass1');
// Verify button state changed
await expect(page.getByRole('button', { name: 'Login' })).toBeEnabled();
await page.getByRole('button', { name: 'Login' }).click();
// Verify routing and success message (Auto-waiting handles network delay)
await expect(page).toHaveURL(/.*dashboard/);
await expect(page.getByRole('heading', { name: 'Welcome, user1' })).toBeVisible();
});Common Mistakes
- Forgetting
await: Callingexpect(locator).toBeVisible()withoutawait. It will silently pass and do nothing. - Using non-retrying assertions for DOM: Fetching text manually and using
expect(text).toBe('abc'). If the text hasn't loaded yet, it fails instantly. Always useawait expect(locator).toHaveText('abc'). - Overusing soft assertions: Using soft assertions for critical flow steps (like checking if login was successful). If login fails, subsequent steps should fail immediately.
Best Practices
- Prefer Web-First (Auto-retrying) Assertions: Always rely on Playwright's built-in
.toHaveText,.toBeVisible, etc. - Use Regex for URLs and Dynamic text: Hardcoding
http://localhost:3000breaks in CI. Use/.*\/dashboard/instead.
Common Interview Questions
- Explain the difference between auto-retrying assertions and standard assertions.
- What happens if you forget to
awaitan auto-retrying assertion? - How do you verify an element does NOT exist on the page?
- What is a soft assertion and when would you use it?
- How would you assert that a button is disabled?
- Why is
await expect(locator).toHaveText('Hello')better thanconst text = await locator.textContent(); expect(text).toBe('Hello')? (Auto-retrying vs Flaky instant check). - How do you assert the exact URL of a page?
- How do you check if a checkbox is selected?
- Explain how to use
expect.poll(). - How do you assert that a specific CSS class is present on an element?
- How do you assert that a list has exactly 10 items?
- What assertion would you use to check the value of an input field?
- How do you check if an element is present in the DOM but completely hidden (e.g.
display: none)? (UsetoBeAttached()). - How can you match text partially, ignoring case sensitivity?
- What timeout does Playwright use for assertions by default, and how can you change it? (Default 5s, pass
{ timeout: 10000 }to the assertion or configure globally).
PART III — NAVIGATION, WAITING, AND TEST STRUCTURE
Section 9: Navigation
What is Navigation?
Navigation in Playwright refers to the process of directing a browser page to a specific URL, handling redirects, interacting with browser history (back/forward), and waiting for the page to reach a specific load state.
Why do we need it?
Every end-to-end test begins with navigating to an application. Modern web applications often involve complex navigation flows, including Single Page Application (SPA) routing, server-side redirects, authentication flows, and dynamic content loading. Understanding how to navigate and wait for the correct state is crucial for writing stable tests.
How does it work?
Playwright communicates with the browser via the DevTools protocol to instruct the page to change its URL. It monitors network traffic and DOM events to determine when the navigation is complete based on user-defined criteria.
page.goto()
The most common way to navigate is using page.goto().
Syntax:
await page.goto(url, options?);Options:
waitUntil: Determines when the navigation is considered successful.timeout: Maximum navigation time in milliseconds (default: 30000ms).referer: The Referer header value.
Load States Explained:
'commit': Considered finished when network response is received and the document started loading.'domcontentloaded': Considered finished when theDOMContentLoadedevent is fired (HTML is parsed, deferred scripts executed).'load': (Default) Considered finished when theloadevent is fired (all resources like images and stylesheets are loaded).'networkidle': Considered finished when there are no network connections for at least500ms. Note: Discouraged for SPAs.
Why networkidle can be problematic for SPAs and modern apps:
Modern applications often have long-polling connections, background telemetry, or continuous data streams (like websockets or Server-Sent Events). In these cases, the network is never truly "idle". Using networkidle can cause tests to hang and timeout unnecessarily. It is generally better to wait for specific locators to become visible or specific network responses.
baseURL Configuration and Relative URLs
You can configure a baseURL in your Playwright config to avoid typing full URLs.
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: 'https://staging.ecommerce.com',
},
});// search.spec.ts
import { test, expect } from '@playwright/test';
test('search works', async ({ page }) => {
// Navigates to https://staging.ecommerce.com/search
await page.goto('/search');
});Other Navigation Methods
page.reload(): Reloads the current page.page.goBack(): Navigates to the previous page in history.page.goForward(): Navigates to the next page in history.
Waiting for URLs and Handling Redirects
Sometimes navigation happens due to UI interaction (e.g., clicking a link or form submission). In these cases, page.waitForURL() is crucial to ensure the app has reached the expected destination, especially handling redirects.
Real-World Navigation Examples
Example 1: Redirect after Login
test('redirects to dashboard after login', async ({ page }) => {
await page.goto('/login');
await page.fill('#username', 'admin');
await page.fill('#password', 'secret');
// Click triggers navigation
await page.click('button[type="submit"]');
// Wait for the URL to change to the dashboard, useful for redirects
await page.waitForURL('**/dashboard');
await expect(page.locator('h1')).toHaveText('Welcome to Dashboard');
});Example 2: Multi-step checkout with history
test('user can navigate back to cart from checkout', async ({ page }) => {
await page.goto('/cart');
await page.click('#checkout-btn');
await page.waitForURL('**/checkout/step1');
// User changes their mind
await page.goBack();
await page.waitForURL('**/cart');
await expect(page.locator('#checkout-btn')).toBeVisible();
});Interview Questions
- Q: What is the default
waitUntilstate forpage.goto()and what does it mean? A: The default is'load'. It means Playwright will wait until theloadevent is fired by the browser, indicating that the HTML document and all external resources (images, stylesheets) have finished loading. - Q: Why shouldn't you use
waitUntil: 'networkidle'in modern web applications? A: Modern apps (SPAs) often have continuous background network activity (telemetry, long-polling, websockets).networkidlewaits for 500ms of zero network activity. If the app constantly polls,networkidlewill never resolve, causing the test to timeout. It's better to wait for specific UI elements or API responses. - Q: How do you configure a base URL so you don't have to hardcode it in every test?
A: By setting the
baseURLproperty in theuseobject withinplaywright.config.ts. Tests can then use relative paths likepage.goto('/login'). - Q: What is the difference between
domcontentloadedandload? A:domcontentloadedfires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.loadfires when the whole page has loaded, including all dependent resources such as stylesheets and images. - Q: You click a button that submits a form and redirects to a success page. How do you reliably wait for this transition?
A: Use
await page.waitForURL('**/success')after clicking the button, or rely on web-first assertions likeawait expect(page).toHaveURL(/.*success/). - Q: What happens if
page.goto()fails (e.g., DNS error)? A: Playwright will throw an error and fail the test unless it is wrapped in atry...catchblock. - Q: How can you simulate a user clicking the browser's back button?
A: Using
await page.goBack(). - Q: How do you navigate to a page with a specific referer header?
A: By passing the
refereroption topage.goto():await page.goto('url', { referer: 'https://example.com' }).
Section 10: Waiting and Synchronization (CRITICAL SECTION)
What is Waiting and Synchronization?
Synchronization is the mechanism by which a test script coordinates its execution pace with the speed of the application under test. Waiting ensures that the test script does not attempt to interact with an element before it is ready (e.g., present in the DOM, visible, enabled).
Why do we need it?
Modern web applications are asynchronous. Data is fetched via API calls, UI updates are driven by frameworks like React/Angular, and animations take time. If a test clicks a "Load Data" button and immediately tries to assert the data is present, it will fail (Race Condition) because the UI hasn't updated yet. Tests must synchronize with the app state.
Playwright's Auto-waiting Mechanism
Playwright sets itself apart with its powerful Auto-waiting feature. Before performing actions (like click, fill, check), Playwright automatically waits for the element to satisfy certain actionability checks.
What it covers (Actionability Checks):
For an action like click(), the locator must be:
- Attached: Element is in the DOM.
- Visible: Element has non-empty bounding box and no
visibility:hidden. - Stable: Element has stopped moving (e.g., CSS animations finished).
- Receives Events: Element is not obscured by other elements.
- Enabled: Element does not have the
disabledattribute.
What it does NOT cover:
- Auto-waiting does not wait for data to load if the UI element is already actionable (e.g., clicking a button that triggers a slow API call; Playwright will click it immediately if the button itself is ready).
- It does not wait for navigation to complete implicitly on custom actions.
- It doesn't apply to methods that just read state, like
locator.isVisible()orlocator.getAttribute().
Explicit Waits
Sometimes, auto-waiting isn't enough, and you need to explicitly wait for a state.
1. Locators and Web-First Assertions (Preferred)
Instead of hard waits, use locators and expect. expect with locators automatically retries until the condition is met or the timeout is reached.
// BEST PRACTICE: Web-first assertion
await expect(page.locator('.success-message')).toBeVisible();2. page.waitForResponse() / page.waitForRequest()
Wait for specific network traffic. Crucial for SPAs.
// Click submit and wait for the API response
const responsePromise = page.waitForResponse(response =>
response.url().includes('/api/login') && response.status() === 200
);
await page.locator('#login-button').click();
const response = await responsePromise;3. page.waitForFunction()
Wait until a JavaScript function executed in the browser returns a truthy value.
// Wait until the window object has a specific property set by the app
await page.waitForFunction(() => window['appLoaded'] === true);4. locator.waitFor()
Wait for an element to satisfy a state ('attached', 'detached', 'visible', 'hidden').
const spinner = page.locator('.loading-spinner');
// Wait for spinner to disappear
await spinner.waitFor({ state: 'hidden' });5. page.waitForTimeout() (WHY THIS IS BAD)
Syntax: await page.waitForTimeout(5000); // Waits exactly 5 seconds
Why it's bad: It causes flaky tests and slows down test suites. If the app takes 5.1 seconds, the test fails. If it takes 0.1 seconds, the test wastes 4.9 seconds. Never use hard waits in production tests. Always wait for a condition (UI state, network).
Common Flaky Test Causes Related to Waiting
- Hard Waits (
waitForTimeout): Environment performance varies; fixed timers are brittle. - Racing Conditions: Clicking a button before the event listener is attached by the frontend framework.
- Animation Interference: Trying to interact with an element while it's sliding in. (Playwright's actionability checks mostly handle this, but complex CSS transitions can sometimes fool it).
- Network Timing: Assuming an API call finishes instantly.
- Stale Elements: A re-render happens between finding the element and acting on it. (Playwright's strict locators re-evaluate, mitigating this significantly compared to Selenium).
Real-world Examples
Problem: Clicking "Add to Cart" triggers a flyout menu after an API call, but the test tries to interact with the flyout too early. Solution:
await page.locator('text=Add to Cart').click();
// Wait for the flyout to be visible before interacting
const flyout = page.locator('#cart-flyout');
await expect(flyout).toBeVisible();
await flyout.locator('text=Checkout').click();Common Mistakes
- Using
page.waitForTimeout(3000)to fix a failing test instead of finding the root cause. - Using
page.waitForSelector()instead of defining a locator and using a web-first assertion (expect(locator).toBeVisible()). - Not awaiting the network response when a click triggers a background API call that updates the UI asynchronously.
- Assuming that if a URL changes, the page is fully ready to be interacted with (need to wait for specific locators).
- Putting the wait action after the trigger in a non-promise way for events. (e.g., clicking, then calling
waitForResponse(). The response might happen between the click and the setup of the wait. You must set up the wait promise before the action).
Interview Questions
- Q: Explain Playwright's auto-waiting mechanism. A: Before interacting with an element (e.g., clicking), Playwright automatically checks if the element is attached to the DOM, visible, stable (not animating), receives events (not obscured), and enabled. It polls these conditions until they are met or the timeout is reached.
- Q: Why is
page.waitForTimeout()considered a bad practice? A: It leads to flaky tests. If the app is slow, the test might fail. If the app is fast, the test wastes time waiting needlessly. It doesn't synchronize with the actual application state. - Q: How do you handle waiting for an element to disappear?
A: Use
await expect(locator).toBeHidden()orawait locator.waitFor({ state: 'hidden' }). - Q: Describe a race condition in test automation and how to prevent it.
A: A race condition occurs when the test attempts an action before the application is in the correct state (e.g., asserting text before the API response populates it). Prevent it by waiting for the API response (
waitForResponse) or using auto-retrying assertions (expect(locator).toHaveText()). - Q: What is a web-first assertion in Playwright?
A: Assertions like
expect(locator).toBeVisible()that are asynchronous and automatically retry until the condition is met or the timeout expires. - Q: If you click a button that makes a slow API call, how do you verify the response was successful?
A: Use
page.waitForResponse(). Set up the promise before clicking, then await the promise after clicking. - Q: What does it mean for an element to be 'stable' in Playwright? A: It means the element's bounding box has remained the same for at least two consecutive animation frames, indicating it has stopped moving or animating.
- Q: How do you wait for a specific text to appear on the page?
A:
await expect(page.locator('text=Your expected text')).toBeVisible(); - Q: You need to wait for a specific variable to be defined on the
windowobject. How do you do that? A: Useawait page.waitForFunction(() => window.myVariable !== undefined); - Q: What is the difference between
locator.waitFor()andpage.waitForSelector()? A:page.waitForSelector()is an older, lower-level API that resolves to an ElementHandle.locator.waitFor()works on locators, which are the modern, preferred way to interact with elements as they are strict and dynamically evaluated. - Q: Why might auto-waiting fail to click an element?
A: If the element is forever hidden by another element (z-index issue), if it never stops animating, if it has
pointer-events: none, or if it's not visible within the timeout. - Q: Can you force a click even if the element is covered by another element?
A: Yes, by bypassing auto-waiting using
await locator.click({ force: true }). - Q: How does Playwright handle waiting during navigation compared to element interaction?
A: Navigation waits for lifecycle events (
load,domcontentloaded), while interaction waits for element actionability (visible, stable, etc.). - Q: What is the default timeout for assertions in Playwright? A: 5000 milliseconds (5 seconds).
- Q: How do you wait for a new tab to open after clicking a link?
A: Set up a wait for the
popupevent:const pagePromise = context.waitForEvent('page'); await clickLink(); const newPage = await pagePromise;
Section 11: Browser, BrowserContext, and Page Deep Dive
What are they?
Playwright's architecture is hierarchical:
- Browser: A single instance of a browser engine (Chromium, Firefox, WebKit). Heavy to launch.
- BrowserContext: An isolated incognito-like session within a browser instance. Fast to create.
- Page: A single tab or window within a BrowserContext.
Why do we need this hierarchy?
Launching a browser takes time and resources. Creating a BrowserContext is extremely fast and provides complete isolation (cookies, local storage). This allows Playwright to run tests in parallel efficiently by launching one browser and creating multiple isolated contexts, rather than launching a new browser for every test.
Deep Dive with Code
import { chromium } from 'playwright';
(async () => {
// 1. Launch Browser (Heavy operation)
const browser = await chromium.launch({ headless: true });
// 2. Create Context (Fast, isolated session)
const context = await browser.newContext({
viewport: { width: 1280, height: 720 },
userAgent: 'My Custom E2E Agent',
geolocation: { longitude: 12.492507, latitude: 41.890251 }, // Rome
permissions: ['geolocation'],
locale: 'it-IT',
timezoneId: 'Europe/Rome'
});
// 3. Create Page (A tab in the context)
const page = await context.newPage();
await page.goto('https://example.com');
// Teardown
await page.close();
await context.close();
await browser.close();
})();Browser Options
headless: Run without UI (default in tests).slowMo: Slows down Playwright operations by specified milliseconds (useful for debugging visually).channel: Specify browser distribution (e.g., 'chrome', 'msedge').
Context Options & Isolation
A BrowserContext provides isolated:
- Cookies
- Local Storage / Session Storage
- Cache
This means Test A and Test B can run concurrently in different contexts without sharing state. Test A logging in will not affect Test B.
Key Context Options:
viewport: Emulate device screen size.geolocation: Mock GPS coordinates.permissions: Auto-grant permissions (e.g., 'notifications', 'camera').storageState: Load pre-authenticated cookies/storage to skip login (Crucial for test speed).extraHTTPHeaders: Add headers to all requests.
Page Events
Pages emit events that you can listen to.
load,domcontentloadedclosepopup(New tab opened)dialog(JavaScriptalert,confirm,prompt)console(Capture browser console logs)
page.on('console', msg => console.log(`Browser logged: ${msg.text()}`));
page.on('dialog', async dialog => {
console.log(dialog.message());
await dialog.accept(); // Auto-accept alerts
});Multiple Pages and Contexts
- Multiple Pages in one Context: Simulates a user with multiple tabs open, sharing the same cookies/session.
- Multiple Contexts in one Browser: Simulates completely different users (e.g., testing chat between User A and User B).
Practical Examples
Simulating Logged-in User via Context (Skipping UI Login)
// Assuming 'auth.json' was generated by an earlier setup script
const context = await browser.newContext({ storageState: 'auth.json' });
const page = await context.newPage();
// User is already logged in!
await page.goto('/dashboard'); Testing Multiple Roles Simultaneously
const adminContext = await browser.newContext({ storageState: 'admin-auth.json' });
const userContext = await browser.newContext({ storageState: 'user-auth.json' });
const adminPage = await adminContext.newPage();
const userPage = await userContext.newPage();
// Admin approves a request, User sees it immediately (testing WebSockets/Polling)
await adminPage.click('#approve-request');
await expect(userPage.locator('.status')).toHaveText('Approved');When to use what in Playwright Test Runner
When using @playwright/test, you rarely launch the browser yourself. The runner provides fixtures.
- Use
pagefixture for standard single-page tests (95% of cases). - Use
contextfixture if you need to manipulate the context (e.g., grant permissions mid-test, or open a secondpagetab in the same session). - Use
browserfixture if you need to create entirely new, isolatedcontextswithin the test (e.g., testing multi-user chat).
Interview Questions
- Q: Explain the hierarchy of Browser, Context, and Page in Playwright. A: A Browser is the engine instance (heavy). A Context is an isolated session within the browser, holding state like cookies and local storage (fast). A Page is a single tab or window within a Context.
- Q: Why does Playwright use BrowserContexts instead of launching a new browser for every test? A: Performance. Launching a browser is resource-intensive. Contexts are lightweight, fast to create, and provide the necessary isolation (cookies, storage) to run independent tests concurrently.
- Q: How do you handle JavaScript
alert()dialogs in Playwright? A: Playwright auto-dismisses dialogs by default. To handle them, add an event listener:page.on('dialog', dialog => dialog.accept()). - Q: How can you test your web app simulating a mobile device in Paris?
A: Create a BrowserContext with
viewportset to mobile dimensions,geolocationset to Paris coordinates,permissions: ['geolocation'], and appropriateuserAgentandlocale. - Q: What is
storageStateand why is it important for test speed? A:storageStateallows you to save and load cookies and localStorage. You can log in once via UI, save the state, and use it in all subsequent tests to completely skip the UI login process, saving massive amounts of time. - Q: How do you test a chat application where User A sends a message to User B?
A: Use the
browserfixture to create two separateBrowserContextinstances. This gives you two isolated sessions. Create a page in each, log them in as different users, and interact between them. - Q: If you open a new tab by clicking a link with
target="_blank", does it share cookies with the original tab? A: Yes, because the new tab (Page) is created within the same BrowserContext. - Q: How do you intercept and log all network requests made by a page?
A:
page.on('request', request => console.log(request.url())); - Q: How can you run a test in a specific browser channel like Microsoft Edge?
A: Set the
channeloption in the Playwright config or launch options to'msedge'. - Q: What is the difference between
page.close()andcontext.close()? A:page.close()closes a single tab.context.close()destroys the isolated session and closes all pages (tabs) associated with that context.
Section 12: Test Structure
What is Test Structure?
Test structure refers to how you organize the code within a single test file using Playwright's testing APIs (test, describe, hooks, annotations).
Anatomy of a Test
Playwright uses the test function from @playwright/test. It takes a title and an async callback containing the test logic. It uses Fixtures (like page) injected into the callback.
import { test, expect } from '@playwright/test';
test('basic test anatomy', async ({ page }) => {
// 1. Arrange / Setup
await page.goto('https://example.com');
// 2. Act / Interact
await page.click('text=More information');
// 3. Assert / Verify
await expect(page).toHaveTitle(/Domain/);
});Grouping and Hooks
test.describe(title, callback): Groups related tests together. Useful for applying hooks to a specific group.- Hooks:
test.beforeAll: Runs once before all tests in a file/describe block. Good for heavy, shared setup (e.g., seeding a database).test.beforeEach: Runs before every test. Good for resetting state, navigating to the starting page.test.afterEach: Runs after every test. Good for cleanup (e.g., deleting a created resource).test.afterAll: Runs once after all tests finish. Good for tearing down infrastructure.
test.describe('Shopping Cart', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/login');
await page.fill('#user', 'testuser');
await page.fill('#pass', 'password');
await page.click('#login-btn');
});
test('add item to cart', async ({ page }) => {
// Starts already logged in
await page.click('#add-item-1');
await expect(page.locator('.cart-count')).toHaveText('1');
});
test('remove item from cart', async ({ page }) => {
// Starts already logged in again (clean page fixture)
// ... logic
});
});Hook Execution Order
describe block
├── beforeAll
├── beforeEach
├── test 1
├── afterEach
├── beforeEach
├── test 2
├── afterEach
└── afterAllRisks of logic in hooks: Putting too much UI logic in beforeAll is dangerous because if the UI fails, all subsequent tests fail or behave unpredictably. UI setup is usually better in beforeEach to ensure a clean slate, or preferably via API/DB to bypass UI flakiness altogether.
Modifiers and Annotations
test.skip(): Conditionally or unconditionally skips a test.test.fixme(): Marks a test as broken. It will be skipped, but signals intent to fix.test.only(): Runs only this test in the file. Useful for debugging.test.fail(): Marks a test that is expected to fail. If it passes, the test runner flags an error.test.slow(): Triples the test timeout. Good for known long-running flows.
test('flaky test currently broken', async ({ page }) => {
test.fixme();
// ...
});
test('only run this on WebKit', async ({ page, browserName }) => {
test.skip(browserName !== 'webkit', 'This feature is WebKit only');
// ...
});test.step()
Groups actions inside a test for better reporting. The HTML report will show these steps hierarchically.
test('complex checkout flow', async ({ page }) => {
await test.step('Login', async () => {
await page.goto('/login');
// ...
});
await test.step('Add to cart', async () => {
// ...
});
});Tags and Annotations
You can tag tests directly in the title using @ for easy filtering via CLI.
// Run via CLI: npx playwright test --grep "@smoke"
test('login works @smoke @regression', async ({ page }) => {
// ...
});Interview Questions
- Q: What is the purpose of
test.describein Playwright? A: It allows grouping related tests together. This is useful for logical organization and for scoping hooks (beforeEach,afterAll) only to the tests within that block. - Q: Explain the difference between
beforeAllandbeforeEach. A:beforeAllruns exactly once per worker before any tests in the file or describe block start.beforeEachruns before every single test in the file or block. - Q: Why shouldn't you use the same
pagefixture insidebeforeAllfor all tests? A: Thepagefixture is designed to be isolated per test.beforeAlldoesn't have access to the test-levelpagefixture. If you manually create a page inbeforeAlland share it, tests are no longer isolated; one test's actions will affect the next, causing flakiness. - Q: How do you run only one specific test while debugging?
A: Append
.onlyto the test declaration:test.only('my test', async ({ page }) => { ... }). - Q: You have a test that takes a long time and keeps timing out, but it's valid. How do you handle it without changing the global timeout?
A: Use
test.slow()inside the test block, which triples the default timeout for that specific test. - Q: How do you group test steps in the HTML report?
A: By wrapping logical blocks of code in
test.step('description', async () => { ... }). - Q: How do you skip a test dynamically based on the browser being used?
A: Using
test.skip(browserName === 'firefox', 'Reason here')inside the test body. - Q: What is the difference between
test.skip()andtest.fixme()? A: Functionally, both skip the test. Semantically,skip()implies the test is intentionally not run (e.g., wrong OS/Browser), whilefixme()implies the test is currently broken and needs attention. - Q: How do you organize tests into suites like Smoke and Regression?
A: Add tags to the test title, e.g.,
test('Login @smoke', ...). You can then run them using the CLI:npx playwright test --grep "@smoke". - Q: What happens if an assertion fails inside an
afterEachhook? A: The test runner marks the test as failed, even if the main test body passed, because teardown failed.
Section 13: Test Organization
What is Test Organization?
Test organization refers to how you structure your files, folders, and shared utilities across a large automation project to ensure it remains maintainable, scalable, and easy to navigate.
Folder Structure Best Practices
Organizing by feature/domain is highly recommended over organizing by action type.
tests/
auth/
login.spec.ts # All login related tests
password-reset.spec.ts
inventory/
product-creation.spec.ts
stock-management.spec.ts
checkout/
payment.spec.ts
shipping.spec.ts
utils/
db-helpers.ts # Shared non-UI functions
api-clients.ts
pages/ # If using Page Object Model
LoginPage.tsTest Suites vs Test Cases
- A Test File (
.spec.ts) usually represents a Suite (a collection of related features). - A
test()block represents a Test Case. - A
test.describe()block represents a Sub-suite.
Test Naming Conventions
Names should describe the action and the expected outcome.
- Bad:
test('login test 1', ...) - Good:
test('should allow user to login with valid credentials', ...) - Good:
test('shows error message on invalid password', ...)
When to Split vs Combine Test Files
- Combine: When tests share identical setup (e.g., all tests require navigating to the User Profile page and asserting different fields).
- Split: When tests grow too long, cover distinct sub-features, or when you want them to run in parallel. (Playwright runs different files in parallel by default; tests within a file run serially unless configured otherwise).
Shared Test Utilities
Don't repeat code. If multiple tests need to generate a random email, create a utility function.
// utils/data-generator.ts
export function generateRandomEmail() {
return `user_${Date.now()}@example.com`;
}
// tests/auth/register.spec.ts
import { generateRandomEmail } from '../../utils/data-generator';
test('register new user', async ({ page }) => {
const email = generateRandomEmail();
// ...
});Interview Questions
- Q: Why is organizing tests by feature better than organizing by type (e.g., putting all 'happy path' tests in one folder and 'error' tests in another)? A: Organizing by feature keeps related context together. When a feature changes, developers only need to look in one directory to update both happy paths and edge cases, improving maintainability.
- Q: Does Playwright run tests in parallel? How does file structure affect this? A: By default, Playwright runs separate test files in parallel across multiple worker processes. Tests within the same file run serially. Therefore, splitting tests into smaller, feature-focused files naturally improves parallelization and execution speed.
- Q: What is the standard file extension for Playwright tests and why?
A:
.spec.tsor.test.ts. This matches standard JavaScript testing conventions (like Jest) and allows Playwright's test runner to automatically discover the test files. - Q: How would you handle a setup step that is required for 50 different test files across your project?
A: I would avoid putting UI steps in a global setup if possible. Instead, I'd use Global Setup to make an API call to prepare the state, or use Playwright's dependencies feature to run a
setup.spec.tsthat saves astorageState(login cookies) to be reused by the 50 test files. - Q: Where should you put helper functions like generating random strings or interacting with the database?
A: Outside the
tests/directory, in a dedicatedutils/orhelpers/folder, to separate test execution logic from utility functions and keep the test folder clean.
PART IV — CONFIGURATION AND TEST PATTERNS
Section 14: Configuration (playwright.config.ts)
What is it?
The playwright.config.ts file is the central nervous system of your Playwright test suite. It dictates how tests are discovered, executed, retried, and reported.
Why do we need it?
Without a configuration file, you would have to pass command-line arguments for every single setting (like browser, viewport, base URL). The config file allows you to define global settings, share configuration across projects (e.g., testing on Chromium, Firefox, WebKit), set up test environments, and manage timeouts consistently.
Core Configuration Properties
Let's break down the most critical properties:
Global Execution Settings
testDir: The directory where Playwright looks for test files (e.g.,'./tests').timeout: The maximum time ONE single test is allowed to run before failing (default: 30000ms).expect.timeout: The maximum time anexpectassertion will wait for a condition to be met (default: 5000ms).fullyParallel: Iftrue, tests in a single file run in parallel. Iffalse(default), tests in a single file run sequentially.forbidOnly: Fails the build iftest.onlyis left in the code. Crucial for CI to prevent running just one test accidentally.retries: Number of times to retry a failing test. Usually0locally, and1or2in CI.workers: Number of parallel workers. Can be a number or a percentage (e.g.,50%). Usually1or undefined locally, and bounded in CI to avoid overwhelming the server.reporter: How results are output. E.g.,'list','html', or an array[['html'], ['junit']].outputDir: Where artifacts (traces, videos, screenshots) are saved.
use: Shared Settings
The use object contains settings that apply to all tests (or all tests in a specific project).
baseURL: The root URL for your tests. Allows you to use relative URLs inpage.goto('/login').trace: Records an execution trace. Options:'off','on','retain-on-failure','on-first-retry'.screenshot: Captures screenshots. Options:'off','on','only-on-failure'.video: Records video. Options:'off','on','retain-on-failure','on-first-retry'.headless: Run browsers without a UI (default is true).viewport: The browser window size, e.g.,{ width: 1280, height: 720 }.actionTimeout: Timeout for actions likeclick(),fill(). (Often left unset to use the test timeout).navigationTimeout: Timeout for page navigations.locale/timezoneId/colorScheme: Emulate user settings (e.g.,'en-GB','Europe/London','dark').extraHTTPHeaders: Add custom headers to all requests (e.g., for API keys or bypassing bot protection in staging).storageState: Path to a JSON file containing cookies/localStorage to reuse authentication.ignoreHTTPSErrors: Ignore invalid SSL certificates (useful for local dev or staging).
Structural Settings
projects: An array configuring different testing targets (e.g., Desktop Chrome, Mobile Safari, Setup scripts).webServer: Automatically start a local dev server before running tests and shut it down afterward.globalSetup/globalTeardown: Paths to scripts that run exactly once before ALL tests and after ALL tests.
Complete Realistic Configuration Example
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
import * as dotenv from 'dotenv';
// Read environment variables from .env file
dotenv.config();
export default defineConfig({
testDir: './e2e',
// Maximum time one test can run (30 seconds)
timeout: 30 * 1000,
expect: {
// Maximum time expect() should wait for the condition to be met (10s)
timeout: 10 * 1000,
},
// Run tests in files in parallel
fullyParallel: true,
// Fail the build on CI if you accidentally left test.only in the source code.
forbidOnly: !!process.env.CI,
// Retry on CI only (2 retries in CI, 0 locally)
retries: process.env.CI ? 2 : 0,
// Opt out of parallel tests on CI to avoid resource constraints
workers: process.env.CI ? 2 : undefined,
// Reporter to use. See https://playwright.dev/docs/test-reporters
reporter: [
['html'],
['list']
],
// Shared settings for all the projects below
use: {
// Base URL to use in actions like `await page.goto('/')`.
baseURL: process.env.BASE_URL || 'http://localhost:3000',
// Collect trace when retrying the failed test.
trace: 'on-first-retry',
// Capture screenshot only when a test fails
screenshot: 'only-on-failure',
// Do not record video by default to save space, unless needed
video: 'off',
// Extra headers for bypassing WAF in staging
extraHTTPHeaders: {
'x-testing-bypass': 'true'
}
},
// Configure projects for major browsers
projects: [
// 1. Setup project for Authentication
{
name: 'setup',
testMatch: /.*\.setup\.ts/,
},
// 2. Desktop Chromium
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
// Use the auth state generated by the setup project
storageState: '.auth/user.json',
},
dependencies: ['setup'], // Ensure setup runs first
},
// 3. Mobile Safari emulation
{
name: 'Mobile Safari',
use: {
...devices['iPhone 13'],
storageState: '.auth/user.json',
},
dependencies: ['setup'],
},
],
// Run your local dev server before starting the tests
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI, // Keep server alive locally
timeout: 120 * 1000,
},
});Development vs CI Configuration
| Setting | Local Development | CI Pipeline |
|---|---|---|
retries | 0 (Fail fast) | 2 (Mitigate flakes) |
forbidOnly | false (Allow focusing) | true (Prevent skipping tests) |
workers | undefined (Use available cores) | 2 or 4 (Bounded to avoid CI crash) |
trace | 'on' or 'retain-on-failure' | 'on-first-retry' (Save space) |
webServer | reuseExistingServer: true | reuseExistingServer: false |
Interview Questions on Configuration
- What is
playwright.config.tsused for? It's the central configuration file where you define test directories, timeouts, parallelization, browsers (projects), reporters, and shared settings (base URL, traces). - What is the difference between
timeoutandexpect.timeout?timeoutis the maximum time an entire single test block (test()) can run.expect.timeoutis the max time a specific assertion (expect(locator).toBeVisible()) will poll before failing. - How do you run tests in parallel in Playwright?
By setting
fullyParallel: truein the config, which runs tests within the same file in parallel. By default, test files run in parallel, but tests inside a file run sequentially. - What does
forbidOnlydo and why use it? It fails the test run iftest.only()is found in the code. It is crucial to set this totruein CI environments to ensure developers don't accidentally commit a targeted test, which would skip the rest of the suite. - How do you handle retries in Playwright?
Use the
retriesconfiguration property. Usually set to 0 locally for fast feedback, and 1 or 2 in CI to handle environmental flakes. - Explain the
workersproperty. It defines the number of parallel OS processes running your tests. In CI, it's often limited (e.g.,workers: 2) so the CI runner isn't overwhelmed by spawning too many browser instances. - What is the
useobject in the configuration? It holds shared context options that apply to all tests, likebaseURL,headless,viewport,trace, andscreenshot. - How does Playwright handle base URLs?
By setting
baseURL: 'https://example.com'in theusesection. In tests, you can then dopage.goto('/login')instead of the full URL. - How do you capture traces on failure?
Set
trace: 'retain-on-failure'in theusesection. - What is the purpose of the
projectsarray? It allows you to run the same suite of tests against multiple configurations, typically different browsers (Chromium, Firefox, WebKit) or devices (Mobile Safari). - How do you manage dependencies between projects?
Using the
dependenciesproperty in a project configuration. E.g., thechromiumproject can depend on thesetupproject, ensuring setup runs first. - What is the
webServerproperty for? It automatically starts a local web server (e.g.,npm run dev) before tests start, waits for the URL to be reachable, and shuts it down after tests finish. - How do you pass extra headers to every request?
Using
use: { extraHTTPHeaders: { 'Authorization': 'Bearer token' } }. - What is
globalSetup? A path to a script that runs exactly once before all tests across all projects. Used for database seeding or global authentication. - How do you configure Playwright to ignore SSL errors?
Set
use: { ignoreHTTPSErrors: true }.
Section 15: Environment Variables
What are Environment Variables?
Environment variables are dynamic values outside your application/test code that affect how the code behaves. In Node.js, they are accessed via the process.env object.
Why do we need them?
- Security: Keep sensitive data (passwords, API keys) out of source control.
- Flexibility: Run the exact same test suite against different environments (Development, Staging, Production) simply by changing variables.
Managing Variables with .env and dotenv
The dotenv package loads variables from a .env file into process.env.
1. Install dotenv:
npm install -D dotenv2. Create a .env file (NEVER COMMIT THIS FILE):
BASE_URL=https://staging.example.com
TEST_USERNAME=testuser@example.com
TEST_PASSWORD=SuperSecretPassword123!
API_KEY=ak_live_123456789
DATABASE_URL=postgresql://user:pass@localhost:5432/testdb3. Create a .env.example file (COMMIT THIS FILE):
BASE_URL=
TEST_USERNAME=
TEST_PASSWORD=
API_KEY=
DATABASE_URL=4. Update .gitignore:
node_modules/
playwright-report/
test-results/
.envUsing Environment Variables in playwright.config.ts
Load dotenv at the very top of your config file.
// playwright.config.ts
import { defineConfig } from '@playwright/test';
import * as dotenv from 'dotenv';
import path from 'path';
// Load different .env files based on a flag, or default to .env
// e.g., cross-env ENV=staging npx playwright test
const envPath = process.env.ENV ? `.env.${process.env.ENV}` : '.env';
dotenv.config({ path: path.resolve(__dirname, envPath) });
export default defineConfig({
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
extraHTTPHeaders: {
'Authorization': `Bearer ${process.env.API_KEY}`
}
},
});Using Environment Variables in Tests
// tests/login.spec.ts
import { test, expect } from '@playwright/test';
test('login with valid credentials', async ({ page }) => {
await page.goto('/login');
// Use environment variables directly in the test
const username = process.env.TEST_USERNAME!;
const password = process.env.TEST_PASSWORD!;
await page.getByLabel('Username').fill(username);
await page.getByLabel('Password').fill(password);
await page.getByRole('button', { name: 'Log in' }).click();
await expect(page.getByText('Welcome back')).toBeVisible();
});CI Environment Variables (GitHub Actions)
In CI pipelines, you don't use .env files. You inject variables directly into the runner environment using secrets.
# .github/workflows/playwright.yml
name: Playwright Tests
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm ci
- run: npx playwright install --with-deps
- run: npx playwright test
env:
BASE_URL: ${{ secrets.BASE_URL }}
TEST_USERNAME: ${{ secrets.TEST_USERNAME }}
TEST_PASSWORD: ${{ secrets.TEST_PASSWORD }}Interview Questions on Environment Variables
- How do you handle different environments (dev, staging, prod) in Playwright?
By using environment variables. I pass a variable like
ENV=stagingand usedotenvto load a.env.stagingfile, configuring thebaseURLand credentials dynamically. - How do you secure passwords and API keys in your automation framework?
I store them as environment variables. Locally, they live in a
.envfile which is added to.gitignore. In CI, they are stored securely in secrets (e.g., GitHub Secrets) and injected at runtime. - What is
process.env? It's a global Node.js object that contains the user environment. It's how we access variables likeprocess.env.BASE_URL. - What happens if you commit a
.envfile containing passwords? It creates a severe security vulnerability. Credentials are leaked into the Git history. You must immediately invalidate/rotate the compromised passwords/keys and remove the file from history. - How do you set an environment variable via the command line?
On Linux/Mac:
BASE_URL=https://prod.com npx playwright test. On Windows PowerShell:$env:BASE_URL="https://prod.com"; npx playwright test. Or cross-platform usingcross-env:npx cross-env BASE_URL=https://prod.com playwright test.
Section 16: Fixtures (IMPORTANT)
What is a Fixture?
A fixture is an environment or state that is prepared before a test runs and cleaned up after it completes. Analogy: Think of a restaurant. A fixture is the waiter clearing the table, placing new silverware, bringing you water (setup), and then clearing your plates when you leave (teardown). You (the test) just show up and eat.
Why Fixtures? (vs. Hooks)
Traditionally, testing frameworks use beforeEach and afterEach hooks. Hooks have problems:
- Scope Bleed: Variables initialized in hooks must be declared with
letoutside the hook, leading to messy state management. - Rigidity: Hooks run for every test in a block, even if a specific test doesn't need that setup.
- Encapsulation: Sharing setup logic across multiple files using hooks is cumbersome.
Fixtures solve this:
- They are requested on-demand. If a test doesn't ask for the fixture, the setup doesn't run.
- They encapsulate setup and teardown together in one place.
- They naturally compose and manage dependencies.
Built-in Fixtures
Playwright provides these by default:
page: An isolated browser tab. Fresh for every test.context: An isolated incognito-like session (holds thepage).browser: The browser instance (shared across tests in a worker).request: An APIRequestContext for making API calls.browserName: The name of the browser running the test ('chromium', 'firefox').
Custom Fixtures
You create custom fixtures by extending the base test object using test.extend<{ fixtureName: Type }>.
The use Function
The core mechanism of a fixture is the use function.
- Code before
use()is the setup. use(value)passes the fixture to the test and pauses.- Code after
use()is the teardown (it runs after the test finishes, even if the test fails).
Complete Example: loggedInPage Fixture
This fixture automatically logs in and provides a ready-to-use page.
// fixtures/auth-fixture.ts
import { test as base, Page } from '@playwright/test';
// Define the types for our fixtures
type AuthFixtures = {
loggedInPage: Page;
testData: { user: string; role: string };
};
// Extend base test
export const test = base.extend<AuthFixtures>({
// 1. A simple data fixture
testData: async ({}, use) => {
// Setup
const data = { user: 'admin', role: 'administrator' };
// Provide to test
await use(data);
// Teardown (nothing to do here)
},
// 2. A complex fixture with setup and teardown, depending on 'page'
loggedInPage: async ({ page }, use) => {
// ---- SETUP ----
console.log('Setting up loggedInPage');
await page.goto('/login');
await page.getByLabel('Username').fill('admin');
await page.getByLabel('Password').fill('password123');
await page.getByRole('button', { name: 'Login' }).click();
await page.waitForURL('/dashboard');
// ---- YIELD ----
// Pass the prepared page to the test
await use(page);
// ---- TEARDOWN ----
console.log('Tearing down loggedInPage');
await page.getByRole('button', { name: 'Logout' }).click();
},
});
export { expect } from '@playwright/test';Using the Fixture in a Test
// tests/dashboard.spec.ts
import { test, expect } from '../fixtures/auth-fixture'; // Import extended test
// This test requests 'loggedInPage'.
// Playwright automatically runs the login setup before the test.
test('view dashboard stats', async ({ loggedInPage, testData }) => {
// Test logic only! No setup clutter.
console.log(`Testing with user: ${testData.user}`);
await expect(loggedInPage.getByText('Welcome, admin')).toBeVisible();
await expect(loggedInPage.locator('.stats-card')).toHaveCount(4);
});
// This test only requests 'page', so the 'loggedInPage' login setup DOES NOT RUN.
test('public homepage', async ({ page }) => {
await page.goto('/');
await expect(page.getByText('Public Content')).toBeVisible();
});Worker-scoped vs Test-scoped Fixtures
- Test-scoped (Default): Created for every test. (e.g.,
page). - Worker-scoped: Created once per worker process and shared across all tests running in that worker. (e.g.,
browser, a database connection pool).
test.extend<TestFixtures, WorkerFixtures>({
// Worker scoped (runs once per worker)
dbConnection: [async ({}, use) => {
const db = await connectToDatabase();
await use(db);
await db.close();
}, { scope: 'worker' }], // Explicitly define scope
});Auto-Fixtures
If you want a fixture to run automatically for every test without the test explicitly requesting it, use auto: true.
test.extend({
clearCache: [async ({ page }, use) => {
await page.evaluate(() => window.localStorage.clear());
await use();
}, { auto: true }],
});Interview Questions on Fixtures
- What is a fixture in Playwright? A fixture is an encapsulated block of setup and teardown logic that provisions an environment or object for a test.
- Name some built-in fixtures.
page,browser,context,request. - Why are fixtures preferred over
beforeEach/afterEachhooks? Fixtures are on-demand (only run if requested), encapsulate setup and teardown together, prevent variable scoping issues (noletdeclarations outside hooks), and are highly reusable across different test files. - Explain how the
use()function works in a custom fixture.use()yields execution to the test block, passing the fixture value to it. Code beforeuse()is the setup; code afteruse()is the teardown, which runs reliably even if the test fails. - What is the difference between a test-scoped and a worker-scoped fixture? A test-scoped fixture runs its setup/teardown for every single test that requests it. A worker-scoped fixture runs once per worker process, sharing its state among all tests executed by that worker (useful for heavy setup like DB connections).
- How do you make a fixture run automatically without requesting it?
By defining the fixture as a tuple and setting
{ auto: true }. - Can a fixture depend on another fixture?
Yes. You can request other fixtures in your custom fixture's parameters (e.g.,
myFixture: async ({ page, context }, use) => { ... }). - How do you share custom fixtures across multiple test files?
By creating a base fixture file that calls
test.extend(), exporting the extendedtestobject, and importing thattestobject in your spec files instead of@playwright/test. - What happens to the teardown code in a fixture if the test fails?
The teardown code (everything after
use()) is still executed. Playwright guarantees teardown execution. - How do you pass data into a test using a fixture?
You define a fixture that yields a data object via
use(dataObject), and then request that fixture by name in the test arguments. - Compare Page Object Model (POM) and Fixtures. POM organizes locators and methods for interacting with a specific page UI. Fixtures provide the infrastructure and setup. They often work together: a fixture can instantiate a Page Object, perform a login on it, and yield the ready-to-use POM instance to the test.
- Can you override an existing built-in fixture?
Yes. You can override
pageorcontextintest.extendto modify default behaviors (e.g., automatically injecting a token into the context before yielding it). - What is fixture chaining? When Fixture A depends on Fixture B, which depends on Fixture C. Playwright resolves the dependency graph and executes setups in the correct order (C -> B -> A) and teardowns in reverse (A -> B -> C).
- How do you type custom fixtures in TypeScript?
You define an interface or type representing your custom fixtures and pass it as a generic to
test.extend<MyFixtures>(). - What is a common mistake when writing fixtures?
Forgetting to call
use(), which causes the test to hang indefinitely. Or putting asynchronous cleanup code beforeuse()instead of after.
Section 17: Authentication (CRITICAL)
The Problem
E2E testing an application requiring authentication usually involves typing a username and password. If you have 50 tests and use beforeEach to log in, you perform the UI login 50 times.
- It's slow: UI login takes 2-5 seconds. 50 * 5s = 4+ minutes just logging in.
- It's flaky: 50 extra UI interactions increase the chance of random network/rendering failures.
- Rate Limiting: Authentication servers might block you for logging in 50 times in a minute.
The Solution: Authentication State (storageState)
Playwright can save the browser's cookies and localStorage to a file.
Instead of logging in via UI for every test, you log in once, save the state, and inject that state into a new browser context for subsequent tests. The app immediately sees the session as authenticated.
Step 1: Create a Setup Project
We configure a specific project in playwright.config.ts to run first and generate the state.
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
projects: [
// 1. The setup project
{
name: 'setup',
testMatch: /.*\.setup\.ts/
},
// 2. The main test project
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
// Tell this project to use the saved state
storageState: '.auth/user.json',
},
// Tell Playwright to run 'setup' before 'chromium'
dependencies: ['setup'],
},
],
});Step 2: Write the Setup Script
Create auth.setup.ts. This is a normal test, but its goal is to save state.
// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
const authFile = '.auth/user.json';
setup('authenticate user', async ({ page }) => {
// 1. Perform UI login
await page.goto('/login');
await page.getByLabel('Username').fill('testuser');
await page.getByLabel('Password').fill('password123');
await page.getByRole('button', { name: 'Log in' }).click();
// 2. Wait for successful login indicator
await expect(page.getByRole('button', { name: 'Logout' })).toBeVisible();
// 3. Save the storage state (Cookies + LocalStorage)
await page.context().storageState({ path: authFile });
});Note: Make sure to add .auth/ to your .gitignore file.
Step 3: Write Tests
Tests now start already logged in!
// tests/dashboard.spec.ts
import { test, expect } from '@playwright/test';
test('verify dashboard data', async ({ page }) => {
// No login required! The context is injected with cookies.
await page.goto('/dashboard');
await expect(page.getByText('Welcome back, testuser')).toBeVisible();
});API/Token-Based Authentication Setup
UI login in setup is good, but API login is even faster. You can bypass the UI entirely in your setup script.
// tests/api-auth.setup.ts
import { test as setup } from '@playwright/test';
const authFile = '.auth/user.json';
setup('authenticate via API', async ({ request, context }) => {
// 1. Make API call to login endpoint
const response = await request.post('https://api.example.com/v1/login', {
data: { username: 'testuser', password: 'password123' }
});
const responseBody = await response.json();
const token = responseBody.token;
// 2. Inject token into browser context manually
await context.addInitScript((token) => {
window.localStorage.setItem('authToken', token);
}, token);
// If using cookies:
// await context.addCookies([{ name: 'session', value: token, domain: 'example.com', path: '/' }]);
// 3. Save state
await context.storageState({ path: authFile });
});Multiple User Roles (Admin vs User)
If you need to test as different roles, generate multiple state files.
auth.setup.tssaves to.auth/admin.jsonand.auth/user.json.- Use custom fixtures to load the specific state per test:
// fixtures.ts
import { test as base } from '@playwright/test';
import fs from 'fs';
export const test = base.extend({
adminPage: async ({ browser }, use) => {
const context = await browser.newContext({ storageState: '.auth/admin.json' });
const page = await context.newPage();
await use(page);
await context.close();
},
userPage: async ({ browser }, use) => {
const context = await browser.newContext({ storageState: '.auth/user.json' });
const page = await context.newPage();
await use(page);
await context.close();
}
});Interview Questions on Authentication
- Why is logging in via UI before every test a bad practice? It makes the test suite excessively slow and introduces flakiness because the UI login process is repeated unnecessarily.
- How does Playwright handle authentication state?
Playwright can capture a browser context's state (cookies and
localStorage) usingcontext.storageState(), save it to a JSON file, and then inject it into new contexts. - What does
storageStatesave? Cookies andlocalStorage. (Note: it does not savesessionStorage). - How do you configure Playwright to run an auth setup script before tests?
By defining a setup project in
playwright.config.tsand setting it as a dependency (dependencies: ['setup']) for the main testing projects. - How can you speed up the setup script itself?
Instead of filling out the UI login form in the setup script, make a direct
request.postAPI call to the authentication endpoint, retrieve the token/cookie, manually add it to the context, and save the state. - How do you handle testing multiple user roles?
Create setup scripts to authenticate and save states for each role (e.g.,
admin.json,editor.json). Then, apply the specific state file either at the project level, in a test file usingtest.use(), or via custom fixtures. - How do you test a "Logout" functionality if the state is injected globally?
You can override the
storageStatefor that specific test block by callingtest.use({ storageState: { cookies: [], origins: [] } })to clear it, or just perform the logout and verify the resulting state without affecting other tests (since contexts are isolated per test). - What happens if the authentication token expires? If tokens expire quickly, saving state to a file might fail during a long test run. You must either configure the app to issue long-lived tokens for testing, or handle re-authentication dynamically within custom fixtures.
- Can
storageStatehandlesessionStorage? No.sessionStorageis tied to a specific browser tab's lifetime. If your app relies on it for auth, you must inject it dynamically usingpage.addInitScript()orpage.evaluate()inside a fixture orbeforeEach. - What files should you add to
.gitignorewhen using this pattern? You should ignore the directory where state files are saved (e.g.,.auth/orplaywright/.cache/) so you don't commit valid session tokens to source control.
Section 18: Page Object Model (POM) — DEEP DIVE
What is POM?
The Page Object Model is a design pattern where you create a class for each page (or significant component) in your application.
Analogy: Instead of directly operating the engine of a car (finding locators and clicking them), you use a dashboard (the Page Object class). The dashboard provides high-level methods (startCar(), accelerate()) and hides the complex wiring.
Why POM?
- DRY (Don't Repeat Yourself): Locators are defined exactly once.
- Maintainability: If the UI changes (e.g., an ID changes from
btn-logintosubmit-login), you update it in ONE place (the class), not in 50 test files. - Readability: Tests read like user journeys (
await loginPage.login('admin', 'pass')) rather than a sequence of DOM interactions. - Separation of Concerns: Tests handle assertions; Page Objects handle interactions and locators.
Disadvantages / Over-engineering
- Abstraction overhead: For very simple apps or single tests, POM adds unnecessary files and boilerplate.
- God Classes: A page object can become huge and unmaintainable if it tries to cover every single element on a massive page. (Solution: Component Objects).
- Wrapping Assertions: Never put
expect()assertions inside Page Objects. Page Objects return state/elements; tests make assertions.
POM Structure
pages/
BasePage.ts (Shared methods like wait for load state)
LoginPage.ts (Login specifics)
DashboardPage.ts (Dashboard specifics)
tests/
login.spec.ts (Uses LoginPage)Complete Example Implementation
1. BasePage.ts
// pages/BasePage.ts
import { Page } from '@playwright/test';
export class BasePage {
readonly page: Page;
constructor(page: Page) {
this.page = page;
}
// Shared navigation method
async waitForPageLoad() {
await this.page.waitForLoadState('networkidle');
}
// Shared UI element
async getToastMessage() {
return this.page.locator('.toast-message');
}
}2. LoginPage.ts
// pages/LoginPage.ts
import { Page, Locator } from '@playwright/test';
import { BasePage } from './BasePage';
export class LoginPage extends BasePage {
// Locators are strictly private or readonly
readonly usernameInput: Locator;
readonly passwordInput: Locator;
readonly loginButton: Locator;
readonly errorMessage: Locator;
constructor(page: Page) {
super(page); // Call BasePage constructor
// Initialize locators in the constructor
this.usernameInput = page.getByLabel('Username');
this.passwordInput = page.getByLabel('Password');
this.loginButton = page.getByRole('button', { name: 'Log in' });
this.errorMessage = page.locator('.error-text');
}
// Action method: Navigation
async navigate() {
await this.page.goto('/login');
}
// Action method: Business logic
async login(username: string, password: string) {
await this.usernameInput.fill(username);
await this.passwordInput.fill(password);
await this.loginButton.click();
}
}3. DashboardPage.ts
// pages/DashboardPage.ts
import { Page, Locator } from '@playwright/test';
import { BasePage } from './BasePage';
export class DashboardPage extends BasePage {
readonly welcomeHeader: Locator;
readonly logoutButton: Locator;
constructor(page: Page) {
super(page);
this.welcomeHeader = page.locator('h1.welcome');
this.logoutButton = page.getByRole('button', { name: 'Logout' });
}
async logout() {
await this.logoutButton.click();
}
}4. The Test File
// tests/login.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
import { DashboardPage } from '../pages/DashboardPage';
test.describe('Login functionality', () => {
test('successful login', async ({ page }) => {
// 1. Initialize Page Objects
const loginPage = new LoginPage(page);
const dashboardPage = new DashboardPage(page);
// 2. Perform actions using POM
await loginPage.navigate();
await loginPage.login('admin', 'password123');
// 3. Assertions remain in the test
await expect(dashboardPage.welcomeHeader).toBeVisible();
await expect(dashboardPage.welcomeHeader).toContainText('Welcome, admin');
});
test('invalid login shows error', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.navigate();
await loginPage.login('wrong', 'user');
// Access POM locator directly for assertion
await expect(loginPage.errorMessage).toBeVisible();
});
});Integrating POM with Fixtures (Advanced & Recommended)
Instantiating new LoginPage(page) in every test gets repetitive. You can combine POM with custom fixtures!
// fixtures/pom-fixture.ts
import { test as base } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
import { DashboardPage } from '../pages/DashboardPage';
type MyPages = {
loginPage: LoginPage;
dashboardPage: DashboardPage;
};
export const test = base.extend<MyPages>({
loginPage: async ({ page }, use) => {
await use(new LoginPage(page));
},
dashboardPage: async ({ page }, use) => {
await use(new DashboardPage(page));
}
});Now the test is perfectly clean:
// tests/login.spec.ts
import { test } from '../fixtures/pom-fixture';
import { expect } from '@playwright/test';
test('successful login', async ({ loginPage, dashboardPage }) => {
await loginPage.navigate();
await loginPage.login('admin', 'password123');
await expect(dashboardPage.welcomeHeader).toBeVisible();
});Interview Questions on POM
- What is the Page Object Model (POM) and why use it? POM is a design pattern that creates an object repository for web UI elements. It separates test logic from page logic, making code reusable, readable, and easy to maintain if locators change.
- Where should assertions (
expect) live when using POM? Assertions must live in the test file, never in the Page Object class. Page objects should handle interactions and return element state/locators. If page objects contain assertions, they lose reusability and violate the separation of concerns. - How do you initialize locators in a Playwright Page Object?
Pass the
pageobject to the class constructor, and definethis.locator = page.locator('...')inside the constructor. - What is a BasePage class used for? It holds common functionality shared across multiple pages, like header/footer elements, generic wait mechanisms, or toast notification handlers. Other page classes inherit from it.
- What are the disadvantages of POM? It introduces structural overhead. For tiny projects, it can be over-engineered. Also, classes can become massive "God Objects" if not properly decomposed into smaller components.
- How does POM differ in Playwright compared to Selenium?
In Selenium, POM often relied on
PageFactoryand@FindByannotations. In Playwright, we simply use theLocatorAPI within the constructor. Playwright locators are strict and auto-waiting, removing the need for explicit wait methods commonly seen in Selenium POMs. - How can you improve POM initialization in Playwright tests?
By using custom fixtures. Instead of calling
new LoginPage(page)in every test, define aloginPagefixture that yields the initialized class. - Can a Page Object method return another Page Object?
Yes, this is called a Fluent Interface. For example,
loginPage.login()could returnnew DashboardPage(this.page). However, this tight coupling can sometimes make code harder to maintain. - Should a Page Object expose
pagedirectly? Generally no, to maintain encapsulation. However, keeping itreadonlyis standard practice so tests can access the underlying page if an edge case requires it. - How do you handle dynamic locators (e.g., a row containing a specific text) in POM?
Instead of defining it in the constructor, create a method that takes parameters:
getUserRow(name: string) { return this.page.getByRole('row', { name }); }
Section 19: Component Object Pattern
What is it?
The Component Object Pattern is an extension of POM. When a Page Object becomes too large, or when a specific UI piece (like a Navigation Bar, a complex Data Table, or a Date Picker) appears on multiple different pages, you extract it into its own Component Object class.
Why?
- Prevents "God Classes" (Page Objects with 2000 lines of code).
- Maximizes reusability across different pages.
Example 1: SidebarComponent
// components/SidebarComponent.ts
import { Locator, Page } from '@playwright/test';
export class SidebarComponent {
readonly container: Locator;
readonly homeLink: Locator;
readonly settingsLink: Locator;
readonly userProfileLink: Locator;
constructor(page: Page) {
// Scope everything to the sidebar container
this.container = page.locator('aside.main-sidebar');
this.homeLink = this.container.getByRole('link', { name: 'Home' });
this.settingsLink = this.container.getByRole('link', { name: 'Settings' });
this.userProfileLink = this.container.locator('.profile-avatar');
}
async navigateToSettings() {
await this.settingsLink.click();
}
}Example 2: TableComponent
Tables are notoriously complex. A component object encapsulates the logic for finding specific rows/cells.
// components/TableComponent.ts
import { Locator, Page } from '@playwright/test';
export class TableComponent {
readonly table: Locator;
readonly rows: Locator;
constructor(page: Page, tableSelector: string) {
this.table = page.locator(tableSelector);
this.rows = this.table.locator('tbody tr');
}
// Dynamic method to find a row containing specific text
getRowByText(text: string): Locator {
return this.rows.filter({ hasText: text });
}
// Method to get a specific action button inside a specific row
async clickActionInRow(rowText: string, actionName: 'Edit' | 'Delete') {
const row = this.getRowByText(rowText);
await row.getByRole('button', { name: actionName }).click();
}
}Integrating Components into Page Objects
You compose Page Objects using these Components.
// pages/UsersPage.ts
import { Page, Locator } from '@playwright/test';
import { SidebarComponent } from '../components/SidebarComponent';
import { TableComponent } from '../components/TableComponent';
export class UsersPage {
readonly page: Page;
readonly sidebar: SidebarComponent;
readonly usersTable: TableComponent;
readonly addUserButton: Locator;
constructor(page: Page) {
this.page = page;
// Instantiate components
this.sidebar = new SidebarComponent(page);
this.usersTable = new TableComponent(page, '#users-data-table');
this.addUserButton = page.getByRole('button', { name: 'Add User' });
}
}Usage in Test
test('delete user', async ({ page }) => {
const usersPage = new UsersPage(page);
await usersPage.sidebar.navigateToSettings();
// Using the table component logic safely
await usersPage.usersTable.clickActionInRow('john_doe', 'Delete');
});Interview Questions on Components
- What is the Component Object Pattern and how does it relate to POM? It's an extension of POM where reusable UI sections (like sidebars, tables, modals) are encapsulated into their own classes. Page Objects are then composed of these components.
- Why would you use a Component Object instead of putting everything in the Page Object? To avoid massive, unmaintainable Page Object classes, and to reuse logic for elements that appear on multiple pages (like a navigation header).
- How do you scope a Component Object to only look inside a specific DOM element?
You define a root container locator (e.g.,
this.container = page.locator('.modal')), and chain sub-locators off it (e.g.,this.container.getByRole('button')). - How do you handle multiple instances of the same component on one page?
Pass a unique selector or root locator to the Component's constructor so it knows which instance to bind to. (e.g.,
new TableComponent(page, '#active-users')vsnew TableComponent(page, '#inactive-users')). - Should a Component Object handle page navigation? Generally no. Components handle interactions within their scope. Navigating entire pages is usually the responsibility of the parent Page Object.
Section 20: Data-Driven Testing and Parameterization
What is Data-Driven Testing?
It's the practice of running the exact same test logic multiple times, but with different input data.
1. Array-Based Parameterization
The simplest way is using standard JavaScript for...of loops around the test() block.
import { test, expect } from '@playwright/test';
// Test Data Array
const searchData = [
{ term: 'Laptop', expectedCount: 15 },
{ term: 'Mouse', expectedCount: 42 },
{ term: 'Keyboard', expectedCount: 20 }
];
test.describe('Search functionality', () => {
// Loop over data array
for (const data of searchData) {
// IMPORTANT: Include the dynamic data in the test name!
test(`should return correct results for ${data.term}`, async ({ page }) => {
await page.goto('/shop');
await page.getByPlaceholder('Search...').fill(data.term);
await page.keyboard.press('Enter');
const resultsText = await page.locator('.results-count').innerText();
expect(resultsText).toContain(`${data.expectedCount} results`);
});
}
});2. External JSON File Parameterization
For large datasets, store the data in a JSON file.
data/users.json
[
{ "username": "admin_user", "role": "admin", "expectedHeader": "Admin Control Panel" },
{ "username": "standard_user", "role": "user", "expectedHeader": "My Dashboard" }
]tests/login-roles.spec.ts
import { test, expect } from '@playwright/test';
import users from '../data/users.json'; // Import JSON directly
for (const user of users) {
test(`Login and verify layout for role: ${user.role}`, async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Username').fill(user.username);
await page.getByLabel('Password').fill('defaultPass123!');
await page.getByRole('button', { name: 'Log in' }).click();
await expect(page.locator('h1')).toHaveText(user.expectedHeader);
});
}3. Environment-Based Test Data
Sometimes data changes based on the environment (staging vs prod). You can use a config object.
const environments = {
staging: { baseUrl: 'https://stg.com', testUser: 'stg_admin' },
prod: { baseUrl: 'https://prod.com', testUser: 'prod_admin' }
};
const currentEnv = process.env.ENV || 'staging';
const config = environments[currentEnv as keyof typeof environments];
test('environment specific test', async ({ page }) => {
await page.goto(config.baseUrl);
await page.getByLabel('User').fill(config.testUser);
// ...
});Common Mistakes
- Forgetting to parameterize the test title: If you do
test('search test')inside a loop, Playwright will complain about duplicate test names, and reporters will be confusing. Always dotest(\search for ${term}`)`. - Putting the loop inside the test:
If the first item fails, the test stops and subsequent items aren't tested. Looping around the test block creates isolated tests.typescript
// BAD PRACTICE test('search multiple items', async ({ page }) => { for (const item of items) { ... } });
Interview Questions on Data-Driven Testing
- What is data-driven testing? It's executing a single test script multiple times with varying datasets to increase test coverage efficiently.
- How do you parameterize tests in Playwright?
By using standard JavaScript loops (
for...oforforEach) around thetest()block. - Why should the loop be outside the
test()block and not inside it? If the loop is outside, Playwright registers each iteration as a separate, independent test. If one dataset fails, the others will still run. If the loop is inside the test block, a failure on the first dataset will abort the test, skipping the rest of the data. - What is crucial when naming parameterized tests?
The test name must include dynamic data from the current iteration (e.g.,
test('Login with user: ${user.name}')). Otherwise, Playwright will have multiple tests with the exact same name, which breaks reporting and test resolution. - How do you read test data from an external file in Playwright?
In TypeScript, you can simply
import data from './data.json'ifresolveJsonModuleis enabled intsconfig.json. Alternatively, you can use the nativefsmodule to read and parse files like CSV or JSON. - How can fixtures be used for data-driven testing? Instead of a loop, you can create a custom fixture that yields specific test data. However, for running the same test multiple times, loops are the standard pattern in Playwright.
- How do you handle test data that differs between staging and production environments?
I use a configuration pattern where I map environment keys (read from
process.env) to specific data objects, or load different.envfiles depending on the environment. - Can you run parameterized tests in parallel?
Yes! Because the loop is outside the
test()block, Playwright treats them as independent tests. IffullyParallel: trueis configured, Playwright will execute the loop iterations simultaneously across workers.
PART V — ADVANCED FEATURES
Section 21: File Handling
What is File Handling in Playwright?
File handling involves testing scenarios where a user uploads files from their local machine to a web application or downloads files from the application to their local machine.
Why do we need it?
Modern applications heavily rely on file operations: uploading profile pictures, attaching documents to forms, downloading reports (PDF/CSV), or exporting data. Testing these flows is critical for complete end-to-end test coverage.
File Upload
1. Single and Multiple File Upload with setInputFiles()
The simplest and most robust way to upload files in Playwright is using the setInputFiles() method on an <input type="file"> element.
Syntax:
await page.locator('input[type="file"]').setInputFiles('path/to/file.txt');
// Multiple files
await page.locator('input[type="file"]').setInputFiles(['file1.txt', 'file2.txt']);
// Remove files
await page.locator('input[type="file"]').setInputFiles([]);Example:
import { test, expect } from '@playwright/test';
import path from 'path';
test('Upload a single profile picture', async ({ page }) => {
await page.goto('https://example.com/profile');
const filePath = path.join(__dirname, '../fixtures/profile.png');
await page.locator('input[type="file"]#avatar-upload').setInputFiles(filePath);
await expect(page.locator('.upload-success')).toBeVisible();
});2. File Chooser Event (page.waitForEvent('filechooser'))
Sometimes, the application uses a custom button that triggers the OS file picker, and there is no visible or easily interactable <input type="file">. In these cases, you must catch the filechooser event.
How it works:
You start waiting for the filechooser event before clicking the button that opens it.
Example:
test('Upload via file chooser', async ({ page }) => {
await page.goto('https://example.com/upload');
// Start waiting for the file chooser BEFORE clicking
const fileChooserPromise = page.waitForEvent('filechooser');
await page.locator('button:has-text("Upload Document")').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(path.join(__dirname, '../fixtures/doc.pdf'));
await expect(page.locator('text=doc.pdf uploaded successfully')).toBeVisible();
});3. Non-standard file inputs
If the page uses drag-and-drop or hidden inputs, setInputFiles() might fail if the input is completely detached from the DOM. However, Playwright handles display: none inputs just fine with setInputFiles().
File Download
Download Event (page.waitForEvent('download'))
When an action (like clicking a button) triggers a file download, Playwright intercepts it and provides a Download object.
How it works:
Like filechooser, you must wait for the download event before clicking the download button.
Example:
import { test, expect } from '@playwright/test';
import fs from 'fs';
import path from 'path';
test('Download an invoice report', async ({ page }) => {
await page.goto('https://example.com/invoices');
// Wait for download event BEFORE clicking
const downloadPromise = page.waitForEvent('download');
await page.locator('text=Download PDF').click();
const download = await downloadPromise;
// Checking filename
expect(download.suggestedFilename()).toBe('invoice_report.pdf');
// Saving downloaded file
const downloadPath = path.join(__dirname, '../downloads', download.suggestedFilename());
await download.saveAs(downloadPath);
// Checking file existence
expect(fs.existsSync(downloadPath)).toBeTruthy();
});Interview Questions
- How do you handle file uploads in Playwright?
Answer: The preferred way is
locator.setInputFiles(). If the input is hidden or custom, we usepage.waitForEvent('filechooser')concurrently with the click action that triggers it. - What happens if you click the upload button before waiting for
filechooser? Answer: The test will likely freeze or timeout. Playwright must attach the event listener before the action that triggers the OS dialog to intercept it correctly. - Can you upload multiple files at once?
Answer: Yes,
setInputFilesaccepts an array of file paths. - How do you clear a selected file from an input?
Answer: By passing an empty array:
setInputFiles([]). - How do you test file downloads?
Answer: Use
page.waitForEvent('download')before triggering the download. Then use the resultingDownloadobject tosaveAs()and verify the file. - How do you verify the downloaded file's name?
Answer: By calling
download.suggestedFilename()on the Download object. - Where are downloaded files saved by default?
Answer: In a temporary directory that gets deleted when the browser context closes. You must explicitly save them using
download.saveAs(path). - How do you assert that a downloaded file actually exists on the disk?
Answer: Use Node.js built-in
fsmodule:fs.existsSync(path)after callingsaveAs().
Section 22: Frames and iFrames
What is an iframe?
An iframe (Inline Frame) is an HTML element that loads another HTML page within the current page. They are essentially a browser window inside a browser window, operating in a separate context.
Why do we need it?
Many modern applications embed third-party content (like Stripe payment forms, YouTube videos, or chat widgets). Standard DOM locators cannot see inside an iframe; you must explicitly tell Playwright to look inside it.
page.frameLocator() - The Primary Approach
This is the modern and recommended way to interact with iframes in Playwright. It treats the iframe like a normal locator that you can chain.
Syntax & Example:
// Nested locators: Frame Locator -> Element Locator
const stripeFrame = page.frameLocator('iframe[title="Secure payment input frame"]');
await stripeFrame.locator('input[name="cardnumber"]').fill('424242424242');page.frame() - By Name/URL (Legacy/Alternative)
You can also grab a frame object by its name attribute or URL.
const frame = page.frame({ name: 'stripe-iframe' });
// or
const frame = page.frame({ url: /.*stripe\.com.*/ });
await frame?.locator('input[name="cvc"]').fill('123');Note: frameLocator is preferred because it's strictly tied to the DOM tree and is more resilient.
Nested iframes
You can chain frameLocator() calls for nested iframes.
await page.frameLocator('#main-frame')
.frameLocator('#nested-frame')
.locator('#target-button')
.click();Common Iframe Issues
- Timing: Iframes take time to load.
frameLocatorautomatically waits for the frame and the element inside it, resolving most timing issues. - Cross-Origin Restrictions: Playwright handles cross-origin frames seamlessly out of the box because it communicates via the Chrome DevTools Protocol, bypassing standard browser CORS limitations for testing.
Real-World Example: Payment Iframe
test('Process payment through Stripe iframe', async ({ page }) => {
await page.goto('https://shop.example.com/checkout');
// The card input is inside an iframe for PCI compliance
const paymentIframe = page.frameLocator('iframe[name="stripe_checkout"]');
await paymentIframe.locator('input[name="cardnumber"]').fill('4242 4242 4242 4242');
await paymentIframe.locator('input[name="exp-date"]').fill('12/25');
await paymentIframe.locator('input[name="cvc"]').fill('123');
await page.locator('button:has-text("Pay Now")').click();
await expect(page.locator('.success-msg')).toBeVisible();
});Interview Questions
- What is an iframe and why is it tricky in automation? Answer: An iframe is an embedded HTML document. It's tricky because normal page locators cannot pierce the iframe boundary; you must explicitly target the iframe context.
- What is the difference between
frameLocator()andframe()? Answer:frameLocator()creates a locator pointing to the iframe element in the DOM and is lazy/auto-waiting.frame()tries to find the frame object immediately by name or URL and might return null if the frame hasn't loaded yet. - How do you locate an element inside a nested iframe?
Answer: By chaining
frameLocator()calls:page.frameLocator('iframe1').frameLocator('iframe2').locator('button'). - Do you need to switch contexts to interact with iframes in Playwright like in Selenium?
Answer: No, Playwright does not require explicit "switching" back and forth. You just use the
frameLocatorin your chain, and Playwright handles the routing. - How does Playwright handle cross-domain iframes? Answer: Out of the box, perfectly. It bypasses same-origin policy restrictions because it drives the browser via DevTools protocol.
- Can you assert that an iframe is visible?
Answer: Yes, you can treat the iframe itself as a standard element:
await expect(page.locator('iframe')).toBeVisible(). - How do you access the parent page from inside a frame object?
Answer: Using
frame.page(). - What happens if the iframe is dynamically added to the page?
Answer:
frameLocator()will automatically wait for the iframe to be attached to the DOM and for the target element inside it to be actionable.
Section 23: Popups, New Tabs, and Windows
What is a popup in Playwright?
A popup is any new browser window or tab that opens as a result of a user action (like clicking a link with target="_blank") or JavaScript (window.open()).
Handling New Tabs/Popups
Playwright treats new tabs and new windows exactly the same—as a new Page object within the same BrowserContext.
page.waitForEvent('popup')
To interact with a newly opened tab, you must capture the popup event while performing the action that opens it.
Example: Opening a product in a new tab
test('Handle product opened in new tab', async ({ page }) => {
await page.goto('https://store.example.com');
// Wait for the popup event concurrently with the click
const popupPromise = page.waitForEvent('popup');
await page.locator('a[target="_blank"]:has-text("Super Widget")').click();
// Get the new page object
const newTab = await popupPromise;
// Wait for the new tab to load and assert
await newTab.waitForLoadState();
await expect(newTab).toHaveTitle(/Super Widget/);
// Interact with the new tab
await newTab.locator('button:has-text("Add to Cart")').click();
// Close the popup
await newTab.close();
});Working with multiple pages simultaneously
Since both the original page and the newTab are objects in your script, you can interact with them interchangeably without explicitly "switching" focus like in older frameworks.
await newTab.locator('button').click(); // Actions in new tab
await page.locator('nav').click(); // Actions in original tabInterview Questions
- How do you handle a link that opens in a new tab?
Answer: Use
const popupPromise = page.waitForEvent('popup');before clicking the link, thenawait popupPromiseto get the newPageobject. - Does Playwright differentiate between a new tab and a new window?
Answer: No, both are treated as new
Pageobjects. - How do you switch back to the original tab?
Answer: You don't need to "switch". You just use the original
pageobject variable to execute commands on it. - What is the difference between
page.waitForEvent('popup')andcontext.waitForEvent('page')? Answer: They achieve the same result.page.waitForEvent('popup')listens specifically on the page that triggered it, whilecontext.waitForEvent('page')listens globally on the browser context for any new page. - How do you handle an OAuth login popup (like "Login with Google")? Answer: Wait for the popup event, use the new page object to fill credentials, submit, and wait for the popup to close automatically or close it manually.
- Can you have more than two pages open at once?
Answer: Yes, a browser context can hold multiple pages. You manage them by keeping references to their respective
Pageobjects. - How do you close a popup window in your test?
Answer: Call
await popupPage.close();. - What happens if you click a
target="_blank"link without waiting for the popup event? Answer: Playwright will open the tab, but you won't have a reference to the newPageobject in your code to interact with it or run assertions on it.
Section 24: Dialogs
What are browser dialogs?
Native browser dialogs are the synchronous popups generated by JavaScript functions: alert(), confirm(), and prompt(), as well as beforeunload warnings.
Note: These are native browser UI, NOT HTML modals.
Dialog Auto-dismissal
CRITICAL: By default, Playwright automatically dismisses (cancels) all native dialogs. If your app relies on accepting a dialog (e.g., clicking "OK" on a delete confirmation), your test will fail unless you explicitly handle it.
page.on('dialog', ...) - Event Listener Approach
To handle dialogs, you set up an event listener.
IMPORTANT: You must set up the listener BEFORE the action that triggers the dialog.
1. Handling alert()
test('Handle alert dialog', async ({ page }) => {
// Setup listener first
page.on('dialog', async dialog => {
expect(dialog.type()).toBe('alert');
expect(dialog.message()).toBe('Data saved successfully!');
await dialog.accept();
});
// Action that triggers the alert
await page.locator('#save-btn').click();
});2. Handling confirm()
test('Handle confirm dialog', async ({ page }) => {
page.once('dialog', async dialog => {
// accept clicks OK, dismiss clicks Cancel
await dialog.accept();
});
await page.locator('#delete-account').click();
});3. Handling prompt()
test('Handle prompt dialog', async ({ page }) => {
page.on('dialog', async dialog => {
expect(dialog.type()).toBe('prompt');
// Provide text input before accepting
await dialog.accept('John Doe');
});
await page.locator('#rename-user').click();
});Interview Questions
- How does Playwright handle native browser dialogs by default? Answer: It automatically dismisses (cancels/closes) them.
- How do you click "OK" on a confirmation alert?
Answer: Set up an event listener
page.on('dialog', dialog => dialog.accept())before triggering the alert. - What is the difference between
page.on('dialog')andpage.once('dialog')? Answer:onlistens continuously for all subsequent dialogs.oncelistens only for the very next dialog and then unregisters itself. - Can you type text into a JavaScript
prompt()using Playwright? Answer: Yes, by passing the string todialog.accept('My text'). - Why did my test fail to catch the dialog even though I wrote
page.on('dialog')? Answer: You likely placed thepage.onlistener after theclick()action that triggered the dialog. Listeners must be attached beforehand.
Section 25: Network Interception (IMPORTANT)
Network interception is one of Playwright's most powerful features. It allows you to intercept outgoing HTTP requests made by the browser and either modify them, block them, or mock their responses.
The Request and Response Objects
- Request: Represents an outgoing HTTP request (URL, headers, method, post data).
- Response: Represents the incoming HTTP response (status, headers, body).
page.route()
The page.route(urlPattern, handler) method intercepts requests matching the pattern.
1. Blocking Requests (route.abort())
Useful for speeding up tests by blocking analytics, images, or third-party tracking.
test('Block images and analytics', async ({ page }) => {
// Block by Regex
await page.route(/\.(png|jpeg|jpg|svg)$/, route => route.abort());
// Block by string matching
await page.route('**/*google-analytics.com/**', route => route.abort());
await page.goto('https://example.com'); // Page loads faster
});2. Mocking Responses (route.fulfill())
Useful for simulating server responses, error states, or testing UI without a real backend.
test('Mock API response', async ({ page }) => {
await page.route('**/api/users', async route => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([{ id: 1, name: 'Mocked User' }])
});
});
await page.goto('https://example.com/users');
await expect(page.locator('.user-card')).toHaveText('Mocked User');
});3. Modifying Requests (route.continue())
Useful for changing headers, removing query params, or modifying POST data before it hits the server.
test('Modify request headers', async ({ page }) => {
await page.route('**/api/data', async route => {
const headers = {
...route.request().headers(),
'X-Custom-Auth': 'secret-token'
};
await route.continue({ headers });
});
});Waiting for Specific API Calls
Instead of static page.waitForTimeout(), you should wait for specific network events.
page.waitForResponse()
test('Wait for specific response', async ({ page }) => {
// Start waiting BEFORE clicking
const responsePromise = page.waitForResponse(
response => response.url().includes('/api/login') && response.status() === 200
);
await page.locator('#submit-btn').click();
const response = await responsePromise;
// You can parse the response body!
const json = await response.json();
expect(json.token).toBeDefined();
});Interview Questions
- What is network interception in Playwright? Answer: The ability to capture, block, modify, or mock HTTP requests and responses made by the browser.
- How do you block all images from loading to speed up tests?
Answer:
await page.route('**/*.{png,jpg,jpeg}', route => route.abort()); - What is the difference between
route.abort(),route.fulfill(), androute.continue()? Answer:abortdrops the request.fulfillprovides a fake mocked response back to the browser.continuelets the request go out to the real server, optionally with modified headers or body. - How do you wait for a specific API call to finish before asserting UI?
Answer: Use
const resPromise = page.waitForResponse('**/api/endpoint');then trigger the UI action, thenawait resPromise. - Can you modify the response coming back from the real server?
Answer: Yes. You can fetch the real response inside the route handler using
route.fetch(), modify the response body, and then return it usingroute.fulfill({ response, body: modifiedBody }). - How do you simulate a 500 Server Error for an API call?
Answer: Intercept the route and use
route.fulfill({ status: 500 }). - What is the difference between matching routes with strings vs regex?
Answer: Strings allow glob patterns (like
**/api/*), which are easier to read. Regex allows complex conditional matching. - Can you read the JSON body of a network response in Playwright?
Answer: Yes, by calling
await response.json()on the response object. - How would you test how the UI handles a slow network request?
Answer: Intercept the route, add a
setTimeoutorawait new Promise(r => setTimeout(r, 5000))inside the handler, and thenroute.fulfill(). - Why should we avoid
waitForTimeoutand usewaitForResponseinstead? Answer:waitForTimeoutis flaky and slow; it waits exactly X seconds regardless of system speed.waitForResponseis dynamic, waiting exactly as long as the network takes, making tests fast and reliable. - How do you clear all active routes?
Answer: Use
await page.unrouteAll(). - Can you intercept requests from an iframe?
Answer: Yes,
page.routeintercepts all requests made by the page, including those originating from iframes. - How do you intercept only POST requests?
Answer: Inside the
page.routehandler, checkroute.request().method() === 'POST'and handle accordingly; otherwise,route.continue(). - How do you pass a HAR file to mock requests?
Answer: Use
await page.routeFromHAR('mockData.har'). - What happens if multiple
page.routehandlers match the same URL? Answer: Playwright evaluates them in reverse order of registration (last registered, first executed).
Section 26: API Testing with Playwright
Why API testing in Playwright?
While primarily an E2E UI tool, Playwright includes a built-in HTTP client (APIRequestContext). This allows you to:
- Test APIs directly (fast, no UI overhead).
- Create test data quickly via API before a UI test.
- Assert database state via API after a UI test.
request fixture vs page.request
requestfixture: Available directly in the test function parameters. It does NOT share cookies/state with the browser context. Great for pure API tests.page.requestorcontext.request: Shares cookies and authentication state with the current browser session. Great for calling APIs as the currently logged-in UI user.
Complete CRUD Example
import { test, expect } from '@playwright/test';
const BASE_URL = 'https://reqres.in/api';
test.describe('API CRUD Operations', () => {
let userId: number;
test('Create a user (POST)', async ({ request }) => {
const response = await request.post(`${BASE_URL}/users`, {
data: {
name: 'John Doe',
job: 'QA Engineer'
},
headers: {
'Accept': 'application/json'
}
});
expect(response.status()).toBe(201);
const body = await response.json();
expect(body.name).toBe('John Doe');
expect(body.id).toBeDefined();
userId = body.id; // Save for next tests
});
test('Get user (GET)', async ({ request }) => {
const response = await request.get(`${BASE_URL}/users/2`, {
params: {
page: 1
}
});
expect(response.ok()).toBeTruthy(); // checks for 200-299 status
const body = await response.json();
expect(body.data.first_name).toBeDefined();
});
test('Update user (PUT)', async ({ request }) => {
const response = await request.put(`${BASE_URL}/users/2`, {
data: {
name: 'John Smith',
job: 'SDET'
}
});
expect(response.status()).toBe(200);
const body = await response.json();
expect(body.job).toBe('SDET');
});
test('Delete user (DELETE)', async ({ request }) => {
const response = await request.delete(`${BASE_URL}/users/2`);
expect(response.status()).toBe(204);
});
});Interview Questions
- Can you do API testing using Playwright?
Answer: Yes, Playwright has a built-in
APIRequestContextaccessible via therequestfixture. - What is the difference between
page.requestand therequestfixture? Answer:page.requestshares cookies and session state with the browser page. Therequestfixture is a fresh, isolated HTTP client with no browser context attached. - How do you pass a Bearer token in an API request?
Answer: Provide a
headersobject in the options:headers: { 'Authorization': 'Bearer token_here' }. - How do you pass query parameters to a GET request?
Answer: Use the
paramsoption object, and Playwright will append them to the URL. - How do you validate the status code of an API response?
Answer:
expect(response.status()).toBe(200);orexpect(response.ok()).toBeTruthy(); - How do you extract the JSON body from a response?
Answer:
const data = await response.json(); - Can Playwright handle multipart form data for API uploads?
Answer: Yes, you use the
multipartoption instead ofdatawhen making the request. - What method is used for partial updates to a resource?
Answer:
request.patch() - How do you chain API requests (e.g., use ID from POST in a subsequent GET)?
Answer: Run the POST,
await response.json(), extract the ID to a variable, and use that variable in the URL of the next request. - Why would you use Playwright for API testing instead of Postman/RestAssured? Answer: It keeps the tech stack unified (TypeScript), allows seamless integration between UI and API tests, and runs extremely fast.
- How do you create an isolated API context with a specific base URL?
Answer: Using
request.newContext({ baseURL: 'https://api.example.com' }). - How do you test API error handling?
Answer: Send invalid data, assert that
response.status()is 400/500, and validate the error message in the JSON body. - Is
request.getsynchronous or asynchronous? Answer: Asynchronous. It must beawaited. - How do you handle API timeouts?
Answer: Pass the
timeoutoption in milliseconds:request.get('url', { timeout: 5000 }). - What does
response.ok()do? Answer: It returns a boolean. True if the status code is in the range 200-299, false otherwise.
Section 27: UI + API Combined Testing
The Power of Combined Testing
Combining UI and API testing is a master-level automation pattern. Instead of using the UI to create a user, log in, navigate to a dashboard, and create a product (which takes 20 seconds and is flaky), you:
- Create the user and product via API (takes 100ms, 100% reliable).
- Open the UI to the product page.
- Perform UI assertions.
- Clean up via API.
Complete Example: Create via API -> Verify UI -> Delete via API
import { test, expect, request } from '@playwright/test';
test.describe('Combined UI/API E2E', () => {
let apiContext;
let testProductId;
test.beforeAll(async () => {
// Create a global API context
apiContext = await request.newContext({
baseURL: 'https://api.store.com',
extraHTTPHeaders: { 'Authorization': 'Bearer admin-token' }
});
});
test('Verify product created via API appears in UI search', async ({ page }) => {
// 1. SETUP: Create test data via API (Fast & Reliable)
const res = await apiContext.post('/products', {
data: { name: 'E2E Test Laptop', price: 999 }
});
const product = await res.json();
testProductId = product.id; // Save ID for cleanup
// 2. TEST: Use UI to verify the data exists and renders correctly
await page.goto('https://store.com');
await page.locator('input[name="search"]').fill('E2E Test Laptop');
await page.locator('button[type="submit"]').click();
// 3. ASSERT: UI validations
const productCard = page.locator('.product-card').first();
await expect(productCard).toContainText('E2E Test Laptop');
await expect(productCard).toContainText('$999');
});
test.afterAll(async () => {
// 4. TEARDOWN: Clean up data via API
if (testProductId) {
await apiContext.delete(`/products/${testProductId}`);
}
});
});Interview Questions
- Why combine UI and API tests? Answer: It drastically reduces test execution time and flakiness. You use the API for test data setup/teardown and only use the UI for the specific feature you are testing.
- Where should API setup/teardown code go?
Answer: In
test.beforeAll/beforeEachfor setup, andtest.afterAll/afterEachfor teardown. - If you create data via API, how do you pass the IDs to the UI test?
Answer: Declare a variable in the test scope (
let itemId;), assign it in thebeforeEachhook, and read it in thetestblock. - Is it better to clean up data in
afterEachor let the database wipe handle it? Answer: Dedicated database wipes are better for overall hygiene, but API teardown inafterEachis a great localized practice to ensure tests don't leave dirty state. - How do you bypass UI login using APIs?
Answer: Use the API to authenticate, retrieve the session cookie or token, and inject it into the browser context using
context.addCookies()or setting local storage before navigating to the UI.
Section 28: Mocking
Why Mocking?
- Isolation: Test the frontend independently of backend bugs/outages.
- Determinism: Tests never fail due to changing database data.
- Speed: No waiting for real database queries.
- Edge Cases: Easily force 500 errors, timeouts, or empty states that are hard to replicate on a real server.
1. Mocking Different Status Codes
You can mock any scenario using page.route and route.fulfill.
test('Test empty state (200 with empty array)', async ({ page }) => {
await page.route('**/api/tasks', route => {
route.fulfill({ status: 200, json: [] });
});
await page.goto('/tasks');
await expect(page.locator('.no-tasks-message')).toBeVisible();
});
test('Test server error (500)', async ({ page }) => {
await page.route('**/api/tasks', route => {
route.fulfill({ status: 500, body: 'Internal Server Error' });
});
await page.goto('/tasks');
await expect(page.locator('.error-toast')).toContainText('Something went wrong');
});2. Mocking Slow Responses (Delay)
Test loading spinners by delaying the mock response.
test('Verify loading spinner', async ({ page }) => {
await page.route('**/api/data', async route => {
// Wait 2 seconds before fulfilling
await new Promise(resolve => setTimeout(resolve, 2000));
await route.fulfill({ status: 200, json: { data: 'ok' } });
});
await page.goto('/dashboard');
await expect(page.locator('.spinner')).toBeVisible();
});3. HAR File Recording and Playback
Playwright can record all network traffic into a HAR (HTTP Archive) file, and in future test runs, use that file to mock all requests automatically!
Record (Update Mode):
Run your tests with --update-snapshots (or specific HAR update flags depending on config) to save the network traffic.
Playback:
test('Use HAR file for mocking', async ({ page }) => {
// Routes all requests matching the HAR file to use saved responses
await page.routeFromHAR('tests/mocks/api-traffic.har', {
url: '**/api/**',
update: false // Set to true to record, false to replay
});
await page.goto('/app');
});Interview Questions
- What is mocking in UI automation? Answer: Simulating backend API responses so the frontend can be tested in isolation.
- How do you mock an API response in Playwright?
Answer: Use
page.route('url', route => route.fulfill({ json: mockData })). - Why is testing edge cases easier with mocking? Answer: Because you can force the API to return 500 errors, 401 Unauthorized, or malformed data instantly, which is difficult to trigger reliably on a real staging server.
- How do you test a loading spinner using mocking?
Answer: Inside the
page.routehandler, introduce a synthetic delay (e.g.,await new Promise(r => setTimeout(r, 2000))) before callingroute.fulfill(). - What is a HAR file and how does Playwright use it?
Answer: An HTTP Archive file. Playwright can record all network traffic to a HAR file and later replay it using
page.routeFromHAR(), automatically mocking all recorded endpoints. - When should you NOT use mocking? Answer: When performing true End-to-End (E2E) testing where the goal is to verify that the frontend, backend, and database all communicate correctly.
- How do you mock a 404 Not Found error?
Answer:
route.fulfill({ status: 404 }) - Can you modify a real API response instead of completely mocking it?
Answer: Yes, you can use
route.fetch()to get the real response, parse the JSON, change a specific field, and then return it withroute.fulfill(). - How do you stop mocking in the middle of a test?
Answer: Call
await page.unroute('**/api/url')to remove the specific route handler. - Does mocking speed up test execution? Answer: Yes, significantly, because the browser doesn't have to wait for real network latency or database query execution on the server.
PART VI — DEBUGGING, REPORTING, AND PRODUCTION READINESS
Section 29: Debugging
What is it?
Debugging in Playwright is the process of finding and resolving issues in your test code or the application under test. Since end-to-end tests interact with complex UIs, network layers, and asynchronous events, robust debugging tools are essential.
Why do we need it?
When a test fails, you need to know exactly why. Was it a timing issue? Did the selector match the wrong element? Did a network request fail? Debugging tools provide visibility into the browser's state at the exact moment of failure.
Tools and Workflows
1. --debug Flag (Playwright Inspector)
Running tests with --debug opens the Playwright Inspector and a visible browser window. The test pauses at the first Playwright action, allowing you to step through the execution.
npx playwright test --debug2. --headed Flag
By default, Playwright runs in headless mode (no UI). To see what's happening on the screen without necessarily pausing, use --headed.
npx playwright test --headed3. Playwright Inspector
The Inspector allows you to:
- Step over actions line-by-line.
- Highlight locators in the live browser.
- Record new tests directly from the UI.
- Explore selectors in real-time.
4. VS Code Playwright Extension
The official extension provides the best DX for debugging:
- Running tests: Click the play button next to the test.
- Debugging with breakpoints: Set breakpoints in TS, right-click, and select "Debug Test".
- Pick locator: Use the extension tool to visually pick elements and get their best Playwright selector.
- Record tests: Generate code by clicking through the application.
5. page.pause() - Programmatic Breakpoint
Insert await page.pause(); in your test code to pause execution and open the Inspector at that specific point.
test('debug login flow', async ({ page }) => {
await page.goto('https://example.com/login');
await page.getByRole('textbox', { name: 'Username' }).fill('user1');
// Pause execution here to inspect the page state
await page.pause();
await page.getByRole('button', { name: 'Login' }).click();
});6. console.log Debugging
You can log variables in your Node.js process, or listen to browser console logs.
page.on('console', msg => console.log(`Browser log: ${msg.text()}`));7. Debugging with Artifacts
- Screenshots: Capture the UI state at the moment of failure.
- Videos: Watch a replay of the test run.
- Traces: The ultimate debugging tool (covered in Section 30).
Debugging in CI
In Continuous Integration (CI), there is no UI, so you cannot use --debug or page.pause(). Instead, you rely entirely on Traces, Videos, Screenshots, and Console Logs saved as artifacts.
Interview Questions
- How do you debug a failing Playwright test?
Answer: Locally, I use the VS Code extension to set breakpoints or use
page.pause()/--debugto step through code. For CI failures, I rely on the Playwright Trace Viewer, videos, and screenshots. - What does
page.pause()do? Answer: It pauses test execution and opens the Playwright Inspector, allowing you to manually explore the page and step through subsequent actions. - How do you view browser console logs during a test?
Answer: By listening to the
consoleevent on the page object:page.on('console', msg => console.log(msg.text())). - Why did a test pass locally but fail in CI? Answer: Usually due to environmental differences: network latency, CPU speed causing race conditions, different screen resolutions, or missing backend data in the CI environment.
- How do you run a specific test in debug mode from the CLI?
Answer:
npx playwright test my-test.spec.ts -g "test name" --debug - What is the difference between
--headedand--debug? Answer:--headedsimply shows the browser UI while the test runs at full speed.--debugopens the Inspector, forces headed mode, and pauses on the first action. - Can you debug network requests in Playwright?
Answer: Yes, using the Inspector's network tab, the Trace Viewer, or programmatically using
page.on('request')andpage.on('response'). - What should you do if an element is not being found in a test?
Answer: I use
await page.pause()right before the failure, use the Inspector's Explore tab to verify the selector, and check if the element is inside an iframe or Shadow DOM. - How do you pick locators efficiently? Answer: Using the "Pick locator" feature in the VS Code extension or the Explore box in the Playwright Inspector.
- Why should you remove
page.pause()before committing code? Answer:page.pause()will halt execution infinitely in headless CI environments, causing the test suite to hang until it hits the global timeout.
Section 30: Trace Viewer (IMPORTANT)
What is a trace?
A trace is a complete, offline recording of a Playwright test execution. It bundles DOM snapshots, network traffic, console logs, and action timings into a single zip file.
Why traces?
Traces are the holy grail for debugging CI failures. Since you cannot attach a debugger to a CI runner, a trace allows you to time-travel through the failed test post-mortem, exactly as it happened.
Trace Configuration Options
Configured in playwright.config.ts under use: { trace: '...' }:
'on'- Always record traces for all tests. (Heavy on disk space/performance).'off'- Never record traces.'on-first-retry'- Record a trace only if a test fails and is retried. (Best for CI).'retain-on-failure'- Record for all, but only keep the file if the test fails.
What trace contains
- Screenshots: A filmstrip of the execution.
- DOM snapshots: You can inspect the DOM of the page at the exact moment before and after every action.
- Network requests: Headers, bodies, and timings for every request.
- Console logs: Browser and Node.js logs.
- Action log: A timeline of Playwright commands.
- Source code: Highlights the exact line of code executing.
Opening Trace Viewer
From the CLI:
npx playwright show-trace trace.zipAlternatively, upload the trace.zip file to trace.playwright.dev (runs entirely locally in your browser).
How trace helps identify flaky failures in CI
By analyzing a trace, you can see if a spinner was blocking the button, if a network request took 10 seconds, or if a dynamic ID changed, all of which explain sporadic CI failures.
Interview Questions
- What is Playwright Trace Viewer? Answer: A GUI tool that allows you to inspect a recorded test run post-execution, providing DOM snapshots, network logs, and source code highlighting for every action.
- How do you enable traces in CI?
Answer: In
playwright.config.ts, setuse: { trace: 'on-first-retry' }or'retain-on-failure'. - Why use 'on-first-retry' instead of 'on'? Answer: Traces consume disk space and slow down tests slightly. 'on-first-retry' ensures traces are only captured when tests actually fail and need debugging.
- How do you view a trace generated in CI?
Answer: Download the
trace.zipartifact from the CI pipeline, and either runnpx playwright show-trace trace.zipor drag-and-drop it intotrace.playwright.dev. - Can you inspect the DOM at a specific point in the past using traces? Answer: Yes, traces capture actual DOM snapshots, so you can inspect elements, compute styles, and see the exact DOM tree as it was during the test action.
- Does trace viewer show network requests? Answer: Yes, it logs all requests, responses, headers, and bodies associated with the browser context.
- What is the difference between a video and a trace? Answer: A video is just a visual recording (mp4). A trace is interactive; you can inspect the DOM, view source code, and analyze network logs.
- What file format is a Playwright trace?
Answer: A
.ziparchive containing metadata, DOM snapshot files, and network payloads.
Section 31: Screenshots and Videos
Screenshots
You can take screenshots of the entire page or specific elements.
// Full page screenshot
await page.screenshot({ path: 'screenshot.png', fullPage: true });
// Element screenshot
await page.getByRole('button').screenshot({ path: 'button.png' });Screenshot on failure:
Configured in playwright.config.ts: use: { screenshot: 'only-on-failure' }.
Visual Testing (toHaveScreenshot): Compares the current page state against a baseline image.
await expect(page).toHaveScreenshot('landing-page.png');Video Recording
Playwright can record videos of the test execution.
Configuration:
use: {
video: 'retain-on-failure', // Options: 'on', 'off', 'on-first-retry', 'retain-on-failure'
videoSize: { width: 1280, height: 720 }
}Where are videos saved?
They are saved in the test-results/ directory by default.
Interview Questions
- How do you capture a screenshot only when a test fails?
Answer: Set
use: { screenshot: 'only-on-failure' }inplaywright.config.ts. - Can you take a screenshot of a specific element instead of the whole page?
Answer: Yes, by calling
.screenshot()on a locator:await locator.screenshot({ path: 'el.png' }). - How does
toHaveScreenshotwork? Answer: It takes a screenshot and compares it pixel-by-pixel to a baseline image stored in the repository. If they differ beyond a threshold, the test fails. - Where do you configure video recording?
Answer: In the
usesection ofplaywright.config.tsusing thevideoproperty. - Why might you prefer traces over videos for debugging? Answer: Videos only show what happened visually. Traces allow you to inspect the DOM, view network logs, and link actions to source code, providing deeper debugging context.
Section 32: Reporting
Types of Reporters
- HTML Reporter: The default and most feature-rich. Generates a standalone web page.
npx playwright show-reportopens it.
- List Reporter: Prints tests in a list format in the console. (Default for CI).
- Line Reporter: Prints a single line, updating as tests run.
- Dot Reporter: Prints a single dot for each test.
- JSON Reporter: Outputs test results as a JSON file, useful for custom integrations.
- JUnit Reporter: Outputs XML format, heavily used in CI tools (Jenkins, GitLab) for native test result UI.
Multiple Reporters Configuration
You can output to multiple reporters simultaneously.
// playwright.config.ts
export default defineConfig({
reporter: [
['list'],
['html', { open: 'never' }],
['junit', { outputFile: 'results.xml' }]
],
});Allure Reporter
A popular third-party reporter (allure-playwright) that generates rich, historical trends and executive-friendly dashboards.
CI Report Artifacts
In CI pipelines (like GitHub Actions), you should always upload the playwright-report/ directory as an artifact so developers can download and view the HTML report for failed builds.
Interview Questions
- What is the default reporter in Playwright? Answer: The HTML reporter locally, and the List/Line reporter in CI depending on the environment variables.
- How do you view an HTML report?
Answer:
npx playwright show-report - How do you output results for Jenkins integration? Answer: Use the JUnit reporter to generate an XML file that Jenkins can parse.
- Can you use multiple reporters at the same time?
Answer: Yes, you can define an array of reporters in
playwright.config.ts. - What is Allure report and why use it with Playwright? Answer: Allure is a third-party reporting framework that provides rich visualizations, historical test trends, and categorizations, which is useful for management and QA leads.
Section 33: Timeouts
Types of Timeouts
- Test timeout: Max time a single
test()block can run. (Default: 30,000ms / 30s). - Expect timeout: Max time
await expect()will poll the DOM before failing. (Default: 5,000ms / 5s). - Action timeout: Max time a single action (like
click()) will wait for actionability. (Default: 0 / no limit, relies on test timeout). - Navigation timeout: Max time for
page.goto(). (Default: 0 / relies on test timeout). - Global timeout: Max time for the entire test suite to finish. (Default: 0 / no limit).
Configuring Timeouts
Global configuration (playwright.config.ts):
export default defineConfig({
timeout: 30000,
expect: {
timeout: 5000,
},
use: {
actionTimeout: 10000,
navigationTimeout: 15000,
}
});Per test:
test('slow test', async ({ page }) => {
test.setTimeout(60000); // 60 seconds
// ...
});Per assertion:
await expect(locator).toBeVisible({ timeout: 10000 });Interview Questions
- What is the default timeout for a Playwright test? Answer: 30 seconds.
- What is the difference between Test timeout and Expect timeout?
Answer: Expect timeout applies to a single assertion polling the DOM (default 5s). Test timeout applies to the entire execution of the
test()block (default 30s). - How do you increase the timeout for a single, specific test?
Answer: Call
test.setTimeout(ms)inside the test body. - If a
click()action cannot find the element, which timeout is hit first? Answer: Usually the test timeout, because action timeout is 0 by default. If action timeout was set to 10s, it would hit the action timeout first. - How do you handle an assertion that takes unusually long, like waiting for an email processing system?
Answer: Pass a specific timeout to the assertion:
await expect(locator).toBeVisible({ timeout: 60000 }).
Section 34: Retries
Why Retries?
Tests in CI can be "flaky" (fail occasionally) due to network hiccups, backend load, or race conditions. Retries give a test a second chance to pass.
Configuration
// playwright.config.ts
export default defineConfig({
// Retry 2 times in CI, 0 times locally
retries: process.env.CI ? 2 : 0,
});How Retries Work
When a test fails and is retried, Playwright completely tears down the browser context and creates a fresh one. It does NOT just re-run the failed line.
Retries as Symptom, Not Cure
Relying heavily on retries masks underlying test stability or application performance issues. A retried test that passes is still a flaky test.
Interview Questions
- How do you configure test retries in Playwright?
Answer: By setting the
retriesproperty inplaywright.config.ts. - Does a retry resume from where the test failed? Answer: No, a retry starts the entire test over from the beginning in a fresh browser context.
- How can you tell inside the test code if it's currently on a retry?
Answer: By checking
test.info().retry. - Why is it common to have
retries: 2in CI but0locally? Answer: Locally, developers want immediate feedback on failures to fix them. In CI, temporary network or environment glitches shouldn't fail the whole build, so retries provide a safety net. - What is the
trace: 'on-first-retry'pattern? Answer: Capturing heavy trace files only when a test fails the first time and triggers a retry. This saves resources while ensuring debugging data is available for flaky/failing tests.
Section 35: Parallel Testing (IMPORTANT)
Workers Concept
Playwright runs tests in parallel using OS-level processes called Workers. Each worker is an independent Node.js process running a separate browser instance, ensuring complete isolation.
fullyParallel Option
By default, tests in different files run in parallel, but tests within the same file run sequentially in a single worker.
Setting fullyParallel: true in playwright.config.ts forces tests within the same file to also run in parallel across multiple workers.
Controlling Workers
// Use exactly 4 workers
workers: 4
// Use 50% of available logical CPU cores
workers: '50%'Serial vs Parallel within a file
// These tests run sequentially, one after another. If one fails, subsequent ones are skipped.
test.describe.serial('Serial tests', () => { ... });
// These tests run concurrently in different workers (if fullyParallel is true)
test.describe.parallel('Parallel tests', () => { ... });Common Problems with Parallel Tests
- Shared data conflicts: Two tests trying to modify the same user account.
- Database contention: Tests locking database tables.
- Port conflicts: Starting a local server on a hardcoded port in
test.beforeAll. - Order dependency: Test B assuming Test A ran first.
Sharding
Sharding distributes the test suite across multiple CI machines.
# Machine 1 runs this:
npx playwright test --shard=1/3
# Machine 2 runs this:
npx playwright test --shard=2/3
# Machine 3 runs this:
npx playwright test --shard=3/3This reduces overall CI pipeline time drastically.
Interview Questions
- How does Playwright achieve parallel execution? Answer: By spawning multiple independent Node.js worker processes, each running its own browser context.
- What is the difference between default parallelism and
fullyParallel? Answer: Default parallelism runs different files in parallel.fullyParallel: trueruns individual tests within the same file in parallel. - What does
test.describe.serialdo? Answer: It groups tests to run sequentially in the exact order they are defined. If one test fails, subsequent tests in the group are skipped. - Why might tests pass locally but fail in parallel? Answer: Due to shared state issues, like multiple tests modifying the same database record or relying on sequential execution order.
- What is Sharding in Playwright? Answer: Splitting the total test suite into fractions to run on completely separate CI machines simultaneously to speed up CI pipelines.
- How do you set workers to use half of your CPU cores?
Answer:
workers: '50%'in the config. - Are parallel workers isolated from each other? Answer: Yes, each worker is a separate Node process with its own memory, browser instance, and browser context.
- Can you limit a specific file to run single-threaded?
Answer: Yes, by not using
fullyParallelglobally, or by wrapping the tests intest.describe.serial. - How do you deal with test data collisions in parallel testing?
Answer: Generate unique test data (e.g., unique email addresses with UUIDs) for every test, or use dynamic data creation in
test.beforeEach. - What is the difference between concurrency and parallelism? Answer: Parallelism (Playwright workers) is simultaneous execution on multiple CPU cores. Concurrency is task interleaving (like async/await) within a single thread. Playwright uses multi-process parallelism.
Section 36: Projects
What are projects?
Projects allow you to run the same test suite with different configurations (e.g., different browsers, different base URLs, different screen sizes).
Configuration Example
export default defineConfig({
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'Mobile Safari',
use: { ...devices['iPhone 12'] },
},
],
});Project Dependencies
You can make one project depend on another. For example, a "Setup" project that logs in and saves auth state, which the "Testing" projects depend on.
{
name: 'setup',
testMatch: /.*\.setup\.ts/,
},
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
dependencies: ['setup'],
}Project Filtering
Run only specific projects from the CLI:
npx playwright test --project=chromiumInterview Questions
- What is a "Project" in Playwright? Answer: A logical grouping of tests run with a specific set of configurations, such as a specific browser, viewport, or environment variable.
- How do you run tests across multiple browsers?
Answer: By defining multiple projects in
playwright.config.ts, each using a different browser device configuration. - How do you run a specific project from the command line?
Answer:
npx playwright test --project="project name" - What are Project Dependencies used for? Answer: They ensure a specific project (like authentication setup or database seeding) completely finishes before the main testing projects begin.
- Can you have staging and production projects in the same config?
Answer: Yes, you can define projects with different
baseURLconfigurations to test different environments. - How does Playwright execute multiple projects? Answer: By default, it runs tests from all projects in parallel using the available workers.
- What is the
devicesobject used in projects? Answer: It is an import from@playwright/testcontaining pre-defined viewport sizes, user agents, and behaviors for hundreds of specific devices. - Can a single test file run in multiple projects?
Answer: Yes, unless specifically filtered out using
testMatchortestIgnore, Playwright runs all tests in all defined projects.
Section 37: Mobile Testing
Device Emulation
Playwright does not run tests on real physical mobile devices. Instead, it uses device emulation within desktop browsers. It emulates viewport size, pixel ratio, User-Agent, and touch events.
devices Object
import { test, devices } from '@playwright/test';
test.use({
...devices['iPhone 13'],
});
test('mobile view test', async ({ page }) => {
// Page is automatically sized to iPhone 13, user agent set to iOS Safari, etc.
});Touch Events
Playwright simulates touch events (tap) instead of mouse clicks when a mobile device is emulated.
await page.getByRole('button').tap();The hasTouch: true configuration enables touch events and hides the mouse cursor.
Limitations
Device emulation does not test actual mobile OS rendering engines (like true iOS WebKit on an ARM chip), hardware quirks, or mobile native keyboard interactions. It tests responsive web design and mobile browser behavior simulation.
Interview Questions
- Does Playwright support testing on real physical iOS/Android devices? Answer: No, Playwright uses browser-based device emulation. (Though you can connect to Android Chrome via ADB experimentally, standard Playwright uses emulation).
- How do you configure a test to run as a mobile device?
Answer: By spreading a profile from the
devicesobject into theuseconfiguration, e.g.,...devices['Pixel 5']. - What aspects of a mobile device does Playwright emulate?
Answer: Viewport size, device pixel ratio, User-Agent string, and touch capabilities (
hasTouch). - Should you use
click()ortap()on mobile emulation? Answer: Playwright'sclick()automatically works, buttap()explicitly simulates a touch gesture which may trigger different event listeners on the web page. - What are the limitations of Playwright's mobile testing? Answer: It cannot catch OS-specific rendering bugs, physical hardware performance issues, or native app integrations since it runs inside a desktop browser engine.
Section 38: Accessibility Testing
Accessibility (a11y) in Playwright
Playwright encourages accessibility through its locator strategy. Using getByRole, getByAltText, and getByLabel forces tests to interact with the page the way a screen reader would.
Basic Assertions
You can assert accessibility tree properties:
await expect(locator).toHaveAccessibleName('Submit');@axe-core/playwright
For comprehensive a11y testing, integrate axe-core.
npm install -D @axe-core/playwrightimport { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
test('should not have any automatically detectable accessibility issues', async ({ page }) => {
await page.goto('https://example.com');
const accessibilityScanResults = await new AxeBuilder({ page }).analyze();
expect(accessibilityScanResults.violations).toEqual([]);
});Playwright is NOT a complete solution
Automated a11y tools (like Axe) can only catch about 20-30% of accessibility issues (like missing ARIA tags or poor contrast). Manual testing with real screen readers is still required.
Interview Questions
- How does Playwright naturally encourage accessibility?
Answer: By prioritizing role-based locators (
getByRole), which requires elements to have proper semantic HTML or ARIA roles. - How can you automate accessibility audits in Playwright?
Answer: By integrating the
@axe-core/playwrightlibrary and runningAxeBuilder.analyze()on the page. - Can automated tools catch all accessibility issues? Answer: No, they only catch programmatic errors. Subjective issues, logical focus orders, and meaningful alt text require human testing.
- What does
toHaveAccessibleNamedo? Answer: It asserts that the accessibility tree computes the specific name for the element, accounting for text content,aria-label, andaria-labelledby. - Why should you avoid
page.locator('#btn')in favor ofpage.getByRole('button', { name: 'Submit' })? Answer: The role locator mimics how an assistive technology finds the element, ensuring the app is accessible while making the test more resilient to DOM changes.
Section 39: Visual Testing
What is Visual Testing?
Visual testing involves taking a screenshot of a web page or component and comparing it to a baseline "golden" image. If the pixels differ beyond a certain threshold, the test fails.
toHaveScreenshot()
test('homepage visual regression', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveScreenshot('homepage.png');
});Updating Snapshots
When you intentionally change the UI, the visual test will fail. You must update the baseline image:
npx playwright test --update-snapshotsConfiguration Options
await expect(page).toHaveScreenshot('image.png', {
maxDiffPixels: 100, // Allow up to 100 pixels difference
maxDiffPixelRatio: 0.01, // Allow 1% of pixels to differ
threshold: 0.2 // Color sensitivity
});Limitations
- Platform differences: Text rendering and anti-aliasing differ between Windows, Mac, and Linux. Screenshots taken on a Mac locally will often fail when compared in a Linux CI environment.
- Dynamic Data: Dates, times, and dynamic graphs will cause false failures unless masked.
- Animations: Blinking cursors or CSS animations can cause flakiness. Playwright automatically attempts to pause animations for screenshots.
Interview Questions
- What is visual regression testing? Answer: Comparing current UI screenshots against baseline images to detect unintended visual changes.
- How do you perform visual testing in Playwright?
Answer: Using
await expect(page).toHaveScreenshot('name.png'). - How do you update baseline images when the UI changes intentionally?
Answer: Run the test command with the
--update-snapshotsflag. - Why might visual tests pass locally but fail in CI? Answer: Because the underlying OS renders fonts, colors, and anti-aliasing slightly differently. Visual tests should ideally be generated and run in the same environment (like a Linux Docker container).
- How do you handle dynamic content (like a clock) in visual testing?
Answer: You can use the
maskoption intoHaveScreenshotto cover dynamic locators with a solid color box before taking the screenshot.
Section 40: Flaky Tests (CRITICAL for interviews)
What is a flaky test?
A flaky test is a test that sometimes passes and sometimes fails without any changes to the code or environment. They destroy trust in the test suite.
Common Causes
- Unstable selectors: Relying on CSS classes that change dynamically (e.g., Tailwind or React styled-components hashes).
- Hard waits: Using
page.waitForTimeout(2000). If the network takes 2001ms, the test fails. - Shared mutable state: Tests altering the same database record simultaneously in parallel execution.
- Race conditions: Clicking a button before the Javascript event listener is attached.
- Test order dependency: Test B failing because Test A didn't run first to set up the data.
- External service dependency: Third-party APIs (like payment gateways) timing out.
- Animations: Trying to interact with an element that is still moving on screen.
- Network instability: CI environments having temporary latency.
- Time-dependent tests: Tests relying on the current clock date/time failing on the last day of the month.
- Browser differences: Quirks specific to WebKit or Firefox rendering.
Strategies for Eliminating Flakiness
- Never use hard waits: Always use Playwright's auto-waiting and web-first assertions (
toBeVisible). - Data isolation: Generate unique data for every single test.
- Mocking: Mock external APIs using
page.route(). - Use Role-based locators: They are resilient to DOM structure changes.
Identifying Flaky Tests
Run a test multiple times to force the flakiness to appear:
npx playwright test --repeat-each=10Interview Questions
- What is a flaky test? Answer: A test that yields inconsistent results (pass/fail) across multiple runs without code changes.
- What is the number one cause of flaky tests? Answer: Race conditions between the test execution and the application's asynchronous state (e.g., clicking an element before it's ready), often caused by using hard waits instead of dynamic waits.
- Why is
page.waitForTimeout()an anti-pattern? Answer: It forces the test to wait a fixed amount of time. If the app is fast, it wastes time. If the app is slow, the test flakes and fails. You should wait for state (toBeVisible) instead. - How does Playwright help prevent flakiness? Answer: With auto-waiting (waiting for elements to be visible, stable, and actionable before interacting) and web-first assertions that automatically retry until the timeout.
- How do you detect flaky tests before merging PRs?
Answer: Run the tests multiple times using the
--repeat-eachflag to ensure consistent passes. - How do you fix a test that fails because a third-party API is sometimes down?
Answer: Intercept the network request using
page.route()and mock the response so the test is isolated and deterministic. - What is test data contamination? Answer: When parallel tests use the same data (like a single user account) and interfere with each other's state, causing random failures.
- If a test relies on today's date, how do you prevent it from failing randomly?
Answer: You mock the browser's clock using
page.clock.setFixedTime()to ensure the test always runs with a consistent deterministic date. - Why might animations cause flakiness? Answer: The element's bounding box is constantly changing during an animation, causing clicks to miss. Playwright usually handles this by waiting for element stability.
- How do traces help with flaky tests? Answer: Since flaky tests are hard to reproduce locally, the trace file from a CI failure provides exact DOM and network state at the moment of failure, revealing the underlying timing issue.
Section 41: Test Isolation
Why test isolation matters
If tests are not isolated, they cannot be run in parallel reliably. One test failing might leave data in a bad state, causing a cascade of false failures in subsequent tests.
BrowserContext Isolation
Playwright achieves runtime isolation out of the box. Every single test() block receives a brand new BrowserContext (essentially an Incognito window) and a new Page.
- Cookies, local storage, and session storage are completely wiped between tests.
Test Data Isolation Strategies
- Dynamic Generation: Use UUIDs or faker libraries to generate unique usernames/emails for every test.
- API Teardown: Use
test.afterEachto call an API to delete the user created during the test. - Database Transactions: Roll back database transactions after each test completes.
API-based setup/teardown
Instead of using the UI to set up state (which is slow and flaky), use backend APIs.
test.beforeEach(async ({ request }) => {
// Quickly seed data via API before the UI test starts
await request.post('/api/seed', { data: { user: 'testUser' }});
});Avoiding test order dependency
Never write tests like this:
test('create user', ...);
test('edit user', ...); // Fails if run in parallel or if 'create user' fails
test('delete user', ...);Each test must create, edit, or delete its own isolated entity independently.
Interview Questions
- What does test isolation mean in Playwright? Answer: Every test runs in a completely fresh browser environment with no shared cookies, local storage, or cache from previous tests.
- How does Playwright implement browser isolation?
Answer: By creating a new
BrowserContextfor every test, which is extremely fast and acts like a new incognito window. - Why is test order dependency bad? Answer: It prevents tests from running in parallel, makes the suite brittle (one failure cascades), and makes individual test debugging impossible.
- How should you handle test data to maintain isolation? Answer: Create unique, independent data for every test run using dynamic IDs, API seeding, or database factories.
- Why should you use an API for test setup instead of the UI? Answer: Setting up data via the UI (like creating a user) is slow and prone to UI flakiness. API calls are fast, reliable, and keep the test focused on the actual scenario being tested.
PART VII — INFRASTRUCTURE AND FRAMEWORK DESIGN
Section 42: CI/CD (IMPORTANT)
What is it?
Continuous Integration and Continuous Deployment (CI/CD) is the practice of automating the integration of code changes and the deployment of applications. In the context of Playwright, CI/CD means running your automated tests automatically whenever code is pushed to a repository or a pull request is created.
Why do we need it?
- Immediate Feedback: Developers know instantly if their changes broke existing functionality.
- Consistency: Tests run in a clean, isolated environment (unlike local machines which may have "works on my machine" issues).
- Quality Gate: Prevents bad code from being merged into the main branch or deployed to production.
- Automation: Removes the need to run tests manually before a release.
GitHub Actions (Complete, Realistic)
GitHub Actions is the CI/CD platform built into GitHub. It uses YAML files to define workflows.
Complete .github/workflows/playwright.yml
name: Playwright Tests
# Run on push to main branch and on any pull request
on:
push:
branches: [ main, master ]
pull_request:
branches: [ main, master ]
# Allow manual trigger
workflow_dispatch:
# Cancel in-progress runs for the same branch to save resources
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
# Use Ubuntu as the base image (fastest and cheapest)
runs-on: ubuntu-latest
# Define a timeout to prevent hanging tests from burning CI minutes
timeout-minutes: 60
# Environment variables available to the tests
env:
BASE_URL: ${{ secrets.BASE_URL }}
TEST_USER: ${{ secrets.TEST_USER }}
TEST_PASSWORD: ${{ secrets.TEST_PASSWORD }}
CI: true
steps:
# 1. Checkout the repository code
- name: Checkout repository
uses: actions/checkout@v4
# 2. Setup Node.js
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm' # Speeds up npm install
# 3. Install dependencies
- name: Install dependencies
run: npm ci
# 4. Install Playwright browsers and OS dependencies
# We only install the browsers needed to save time.
# Playwright provides a command to install all necessary system dependencies (--with-deps)
- name: Install Playwright Browsers
run: npx playwright install --with-deps chromium
# 5. Run the tests
- name: Run Playwright tests
run: npx playwright test
# 6. Upload the HTML report (even if tests fail)
- name: Upload Playwright HTML Report
uses: actions/upload-artifact@v4
if: always() # Ensure this runs regardless of test pass/fail
with:
name: playwright-report
path: playwright-report/
retention-days: 14
# 7. Upload tracing/videos (usually saved in test-results)
- name: Upload Test Results (Traces/Videos)
uses: actions/upload-artifact@v4
if: failure() # Only upload if tests fail to save storage
with:
name: test-results
path: test-results/
retention-days: 14Line-by-Line Explanation:
on: [push, pull_request]: Triggers the workflow when code is pushed to main or a PR is created.concurrency: Cancels previous running jobs for the same PR if a new commit is pushed. Saves CI minutes.runs-on: ubuntu-latest: Linux environments are highly recommended for Playwright CI because they are fast and support all browsers perfectly.env: Maps GitHub Secrets to environment variables that Playwright can access viaprocess.env.actions/checkout@v4: Clones your code into the CI runner.actions/setup-node@v4: Installs Node.js and cachesnode_modulesbased onpackage-lock.json.npm ci: "Clean Install". It installs dependencies exactly as specified inpackage-lock.json. Faster and more reliable thannpm installin CI.npx playwright install --with-deps chromium: Installs the Playwright browser binaries and, crucially, any required Linux system libraries (--with-deps).npx playwright test: Executes the test suite.actions/upload-artifact@v4: Saves files generated during the CI run so you can download them later.if: always()is critical so you get the report even when tests fail.
Sharding across multiple jobs
If your test suite takes 30 minutes, you can split it across 5 machines to run in 6 minutes.
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
shardIndex: [1, 2, 3, 4, 5]
shardTotal: [5]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm ci
- run: npx playwright install --with-deps
# Pass the shard arguments to the test command
- name: Run tests
run: npx playwright test --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
- uses: actions/upload-artifact@v4
if: always()
with:
name: blob-report-${{ matrix.shardIndex }}
path: blob-report
retention-days: 1Note: You would need a separate job to merge the blob reports into a single HTML report.
GitLab CI
# .gitlab-ci.yml
stages:
- test
# Use the official Playwright Docker image
image: mcr.microsoft.com/playwright:v1.43.0-jammy
playwright_tests:
stage: test
script:
- npm ci
# Browsers are already installed in the image, so we skip `playwright install`
- npx playwright test
artifacts:
when: always
paths:
- playwright-report/
expire_in: 14 daysJenkins
// Jenkinsfile
pipeline {
agent {
docker {
image 'mcr.microsoft.com/playwright:v1.43.0-jammy'
args '-u root'
}
}
stages {
stage('Install dependencies') {
steps {
sh 'npm ci'
}
}
stage('Run Tests') {
steps {
sh 'npx playwright test'
}
}
}
post {
always {
archiveArtifacts artifacts: 'playwright-report/**/*', allowEmptyArchive: true
}
}
}Azure DevOps
# azure-pipelines.yml
trigger:
- main
pool:
vmImage: 'ubuntu-latest'
steps:
- task: NodeTool@0
inputs:
versionSpec: '20.x'
displayName: 'Install Node.js'
- script: |
npm ci
displayName: 'Install Dependencies'
- script: |
npx playwright install --with-deps
displayName: 'Install Playwright Browsers'
- script: |
npx playwright test
displayName: 'Run Playwright tests'
env:
CI: 'true'
- task: PublishPipelineArtifact@1
condition: always()
inputs:
targetPath: 'playwright-report'
artifact: 'playwright-report'
publishLocation: 'pipeline'General CI Considerations
- Headless Mode: CI servers usually do not have a graphical interface. Tests MUST run in headless mode (which is Playwright's default).
- Resource Allocation: Browsers consume CPU and RAM. If your CI runner has limited resources (e.g., 2 cores, 4GB RAM), you may need to reduce the number of parallel workers (
workers: 2orworkers: 1) inplaywright.config.tsto avoid out-of-memory crashes. - Flakiness in CI: Tests that pass locally but fail in CI often do so because CI environments are slower. Ensure you are using robust assertions (
toBeVisible,toHaveText) rather thanwaitForTimeout. - Environment Variables: Never commit passwords. Use GitHub Secrets / GitLab CI variables and pass them as environment variables.
Interview Questions
-
How do you integrate Playwright with GitHub Actions? Answer: By creating a
.github/workflows/ymlfile. The key steps are: checking out code, setting up Node, runningnpm ci, runningnpx playwright install --with-depsto get browsers and OS dependencies, runningnpx playwright test, and finally usingactions/upload-artifactto save the HTML report. -
Why do tests pass locally but fail in CI? Answer: CI runners are usually virtual machines with less CPU/RAM than a developer's laptop, making them slower. This exposes race conditions in tests. If a test doesn't properly wait for an element (e.g., relying on implicit speed rather than
waitForor web-first assertions), it will fail in CI. Network latency in CI can also affect API calls. -
What does
--with-depsdo inplaywright install? Answer: It not only downloads the browser binaries (Chromium, Firefox, WebKit) but also installs the required Linux system-level dependencies (like font libraries, graphics drivers, etc.) needed to run those browsers in headless mode on a bare-metal CI runner. -
How do you handle secrets (passwords) in Playwright tests running in CI? Answer: I store the secrets in the CI platform's secret manager (e.g., GitHub Secrets). I then map them to environment variables in the workflow YAML file. In my Playwright tests, I access them using
process.env.MY_SECRET. -
How can you speed up Playwright test execution in CI? Answer: 1. Run tests in parallel using workers. 2. Use CI sharding to split the test suite across multiple CI machines. 3. Cache
node_modules. 4. Usetest.describe.configure({ mode: 'parallel' })to run tests within the same file concurrently. -
How do you debug a test that only fails in CI? Answer: First, I enable Playwright Tracing (
trace: 'retain-on-failure'). I download the trace artifact from the CI run and view it usingnpx playwright show-trace. This gives me a DOM snapshot, network logs, and console logs at the exact moment of failure. -
What is test sharding? Answer: Sharding is a feature that allows you to divide your test suite into multiple smaller parts and run them simultaneously on different CI machines. For example,
npx playwright test --shard=1/3runs the first third of the tests. -
Why is
npm cipreferred overnpm installin pipelines? Answer:npm ci(clean install) deletes thenode_modulesfolder and installs exactly the versions specified inpackage-lock.json. It guarantees a reproducible build, whereasnpm installmight update minor versions of dependencies and rewrite the lock file. -
How do you ensure the Playwright report is generated even if tests fail? Answer: In GitHub Actions, I use the
if: always()condition on the upload-artifact step. This ensures the step runs regardless of whether the previous step (the test run itself) succeeded or failed. -
What is the difference between running Playwright on Ubuntu vs Windows in CI? Answer: Ubuntu is significantly faster, cheaper, and consumes fewer resources for spinning up containers/VMs. Playwright is highly optimized for Linux, making it the standard best practice for CI.
Section 43: Docker
What is it?
Docker is a platform that allows you to package applications and their dependencies into standardized units called containers.
Why Docker for Playwright?
When running tests across different machines (Developer A's Mac, Developer B's Windows, Jenkins Linux server), you might encounter environment differences (missing fonts, different OS libraries). Docker ensures 100% consistency. The environment where the tests run is exactly the same everywhere.
Official Playwright Docker Images
Microsoft maintains official Docker images for Playwright. They come pre-installed with Node.js, Playwright, Chromium, Firefox, WebKit, and all necessary OS dependencies.
Example: mcr.microsoft.com/playwright:v1.43.0-jammy (based on Ubuntu 22.04 Jammy).
Dockerfile Example
# Use the official Playwright image as the base
FROM mcr.microsoft.com/playwright:v1.43.0-jammy
# Set the working directory inside the container
WORKDIR /app
# Copy package.json and package-lock.json
COPY package*.json ./
# Install npm dependencies (Playwright is already in the image, but your project needs its dependencies)
RUN npm ci
# Copy the rest of the project files
COPY . .
# Command to run tests
CMD ["npx", "playwright", "test"]docker-compose.yml Example
version: '3.8'
services:
playwright-tests:
build: .
# Map a local folder to get the report out of the container
volumes:
- ./playwright-report:/app/playwright-report
- ./test-results:/app/test-results
environment:
- CI=true
- BASE_URL=https://staging.example.comRun it via: docker-compose up --build
CI with Docker
Many CI systems (like GitLab CI or CircleCI) run jobs directly inside Docker containers. In this case, you don't need a Dockerfile. You just specify the Playwright image in your CI YAML (as shown in the GitLab example in Section 42).
Interview Questions
-
Why would you use the official Playwright Docker image instead of a generic Node image? Answer: The official Playwright image comes pre-installed with the browser binaries (Chromium, Firefox, WebKit) and all the Linux system-level dependencies required to run them headlessly. If I used a generic Node image, I would have to manually run
apt-get installfor dozens of system libraries. -
How do you extract the Playwright report from a Docker container? Answer: Because the container's file system is isolated, I use Docker Volumes to map a directory on my host machine to the directory inside the container where the report is generated (e.g.,
-v $(pwd)/playwright-report:/app/playwright-report). -
What is the
jammytag in the Playwright Docker image? Answer: It refers to Ubuntu 22.04 LTS (Jammy Jellyfish). It indicates the underlying Linux distribution used for the base image. -
Can you run Playwright tests in UI mode (
--ui) inside a Docker container? Answer: Generally no, because Docker containers lack a display server (X11/Wayland) by default. Docker is meant for headless execution. While it is technically possible to forward X11 to the host, it is complex and defeats the purpose. Docker should be used for headless CI execution. -
Why do visual regression tests (screenshots) sometimes fail locally but pass in Docker? Answer: Font rendering, anti-aliasing, and pixel calculations differ slightly between macOS, Windows, and Linux. If baseline screenshots were generated on a Mac, they might fail when compared on a Linux Docker container. The best practice is to always generate baseline screenshots inside the Docker container to ensure consistency.
Section 44: Git/GitHub Workflow
The Automation Workflow
+---------------------+
| Developer writes |
| or updates test |
+---------+-----------+
|
v
+---------------------+
| Git commit & push |
| to feature branch |
+---------+-----------+
|
v
+---------------------+
| Create Pull Request |
| against main branch |
+---------+-----------+
|
v
+---------------------+ +------------------------+
| CI Pipeline Starts | ---> | Playwright Tests Run |
+---------+-----------+ +-----------+------------+
| |
v v
+---------------------+ +------------------------+
| Report Generated | <--- | Pass / Fail Status |
+---------+-----------+ +------------------------+
|
+-------------------------+
| |
v v
+---------------------+ +-----------------------+
| Status: PASS | | Status: FAIL |
| Reviewers approve | | Fix code, push again |
| Merge to main | +-----------------------+
+---------------------+Branching Strategies for Test Code
If test code lives in the same repository as the application code (Monorepo):
- Developers modify application code and test code in the same branch.
- CI runs the tests against the new application code.
- If tests pass, everything is merged together.
If test code is in a separate repository (Multi-repo):
- You must manage versions carefully. Usually, test branches mirror application branches.
PR Checks
In GitHub, you can configure Branch Protection Rules to require that the Playwright CI workflow passes before a Pull Request can be merged. This acts as a strict quality gate.
Code Review for Tests
When reviewing Playwright tests, look for:
- Flakiness risks: Use of
waitForTimeout, fixed waits, or missing assertions. - Maintainability: Hardcoded locators instead of Page Objects or proper data-testid attributes.
- Readability: Clear test names and organized step descriptions.
Interview Questions
-
Should automated tests live in the same repository as the application code? Answer: Yes, a monorepo is highly preferred. It ensures tests are versioned alongside the code they test. When a developer changes a feature, they update the test in the same PR, and CI validates both simultaneously.
-
How do you prevent broken code from being merged? Answer: By setting up CI pipelines that run Playwright tests on every Pull Request, and enforcing "Branch Protection Rules" in GitHub/GitLab that block merging if the CI status checks fail.
-
What do you look for when doing a code review on a colleague's Playwright test? Answer: I look for strict assertions (web-first assertions), the absence of hardcoded sleeps (
waitForTimeout), correct usage of locators (preferring user-facing attributes like text or roles over complex XPaths), and ensuring test independence (no shared state between tests).
Section 45: Database Testing
How Playwright interacts with databases
Playwright is a frontend testing tool. It interacts with the browser. It does not have built-in methods for connecting to SQL or NoSQL databases.
However, since Playwright runs in a Node.js environment, you can install standard Node.js database drivers (e.g., pg for PostgreSQL, mongodb for MongoDB) and write JavaScript/TypeScript to query the database within your test setup/teardown.
API-Based Data Setup (Preferred)
The best practice for setting up test data is to use the application's APIs (REST/GraphQL) rather than direct database queries.
- Why? APIs encapsulate business logic. If you insert directly into a DB, you might miss triggering related services, caches, or background jobs. APIs are safer and less fragile to schema changes.
Direct DB Access Considerations
Sometimes APIs don't exist for test setup, or you need to verify an asynchronous database write.
import { test, expect } from '@playwright/test';
import { Client } from 'pg'; // Node Postgres client
let dbClient: Client;
test.beforeAll(async () => {
dbClient = new Client({ connectionString: process.env.DB_URL });
await dbClient.connect();
});
test.afterAll(async () => {
await dbClient.end();
});
test('user registration saves to DB', async ({ page }) => {
await page.goto('/register');
await page.fill('#email', 'test@example.com');
// ... submit form ...
// Direct DB assertion (use carefully!)
const res = await dbClient.query("SELECT * FROM users WHERE email = 'test@example.com'");
expect(res.rows.length).toBe(1);
});Test Data Management Strategies
- Create before test, clean up after test: Use
beforeEachto seed data, andafterEachto delete it. - Unique Data Per Test (Best Practice): Use UUIDs or timestamps to generate unique usernames/emails (e.g.,
testuser-${Date.now()}@example.com). This prevents parallel tests from interfering with each other and reduces the need for complex cleanup. - Database Seeding: Run a script before the test suite starts to populate the database with known, static reference data (categories, products).
Interview Questions
-
Is Playwright a database testing framework? Answer: No, Playwright is a UI testing framework. However, because tests are written in Node.js, we can import database libraries to set up data or verify backend states if absolutely necessary.
-
Why is it preferred to use APIs for test data setup rather than direct SQL queries? Answer: APIs execute the full business logic layer, ensuring relationships, caches, and events are processed correctly. Direct SQL queries bypass the application layer, which can leave the database in an invalid state and make tests brittle to DB schema changes.
-
How do you handle test data when running tests in parallel? Answer: I ensure data isolation. Each test creates its own unique data, usually by appending a UUID or timestamp to string values (like emails or project names). I never share a single mutable record across parallel tests to avoid race conditions.
-
How do you clean up data created during a test? Answer: I typically clean it up in an
afterEachhook or via an API call at the end of the test. However, relying on cleanup is risky because if a test crashes, cleanup might not run. Generating unique data per test is a more robust approach. -
How would you assert that a PDF was generated by a background worker after clicking "Export" on the UI? Answer: Since it's a background process, the UI might not show it immediately. I could either poll an API endpoint that checks the status, or connect to the database in my test and poll the database table to check if the export record status changed to 'completed'.
Section 46: Test Automation Framework Architecture
Realistic Enterprise Framework Design
A robust framework organizes code for maintainability, reusability, and scale.
playwright-framework/
│
├── tests/ # Actual test files (.spec.ts)
│ ├── auth/ # Grouped by feature/domain
│ ├── products/
│ └── api/
├── pages/ # Page Object Models
│ ├── LoginPage.ts
│ ├── DashboardPage.ts
│ └── BasePage.ts # Common page methods
├── components/ # Reusable UI components across pages
│ ├── Navbar.ts
│ └── Table.ts
├── fixtures/ # Custom Playwright fixtures
│ ├── auth.fixture.ts
│ └── pages.fixture.ts
├── utils/ # Helper functions
│ ├── helpers.ts # e.g., generateRandomString()
│ └── constants.ts
├── test-data/ # Static data files
│ ├── users.json
│ └── env.json
├── api/ # API clients for test setup
│ └── ApiClient.ts
├── .github/workflows/ # CI/CD pipelines
│ └── playwright.yml
├── playwright.config.ts # Main Playwright configuration
├── .env # Local environment variables (not committed)
└── package.json # Dependencies and scriptsExplanation of Folders & Design Decisions
tests/: Contains only the actual test logic (Arrange, Act, Assert). It should be clean and readable. No complex selectors here.pages/(Page Object Model): Encapsulates page-specific locators and actions. If the UI changes, you update the Page Object, not the hundreds of tests.components/: Represents UI elements present on multiple pages (like headers, footers, sidebars). Pages can compose these components.fixtures/: Playwright's dependency injection system. This is where we inject initialized Page Objects and auth states into tests.api/: Contains logic to interact with the backend APIs to set up prerequisites (e.g., creating a user via API before testing the UI login)..env: Manages environment-specific configurations (URLs, credentials). Handled viadotenvpackage.
Example Code from Key Files
pages/BasePage.ts
import { Page, Locator } from '@playwright/test';
export abstract class BasePage {
constructor(protected page: Page) {}
async navigate(path: string) {
await this.page.goto(path);
}
// Shared methods like wait for loaders, handle common popups
}pages/LoginPage.ts
import { Page, Locator, expect } from '@playwright/test';
import { BasePage } from './BasePage';
export class LoginPage extends BasePage {
readonly usernameInput: Locator;
readonly passwordInput: Locator;
readonly loginButton: Locator;
readonly errorMessage: Locator;
constructor(page: Page) {
super(page);
this.usernameInput = page.getByRole('textbox', { name: 'Username' });
this.passwordInput = page.getByRole('textbox', { name: 'Password' });
this.loginButton = page.getByRole('button', { name: 'Login' });
this.errorMessage = page.locator('.error-msg');
}
async login(user: string, pass: string) {
await this.usernameInput.fill(user);
await this.passwordInput.fill(pass);
await this.loginButton.click();
}
}Interview Questions
-
What is the Page Object Model (POM) and why use it? Answer: POM is a design pattern that creates an object repository for web UI elements. It separates the test logic (assertions) from the UI logic (locators and interactions). This reduces code duplication and drastically improves maintainability when the UI changes.
-
How does Playwright's Fixture pattern improve upon the standard Page Object Model? Answer: Standard POM requires you to manually instantiate classes in every test (
const loginPage = new LoginPage(page)). Playwright fixtures inject pre-initialized Page Objects directly into the test function arguments, reducing boilerplate and managing setup/teardown automatically. -
Why separate
components/frompages/? Answer: Many UI elements (like Navigation Bars or generic Data Tables) appear on multiple pages. Creating aNavbarComponentprevents duplicating the navbar locators inDashboardPage,SettingsPage, etc. -
Where would you store API calls used to create test data? Answer: In a dedicated
api/orservices/directory. Tests should call these helper methods (e.g.,await ApiClient.createOrder(userId)) to arrange data, keeping the test file clean. -
How do you handle different environments (dev, staging, prod)? Answer: I use environment variables via
.envfiles and thedotenvpackage. I configure thebaseURLinplaywright.config.tsdynamically based onprocess.env.TEST_ENV. -
Why keep locators in the constructor of a Page Object? Answer: It initializes the locators when the object is created, keeping all selectors in one centralized place at the top of the file. Playwright locators are lazy-evaluated, so creating them in the constructor does not perform any DOM action.
-
How do you structure test files in the
tests/directory? Answer: I organize them logically by feature or domain (e.g.,auth/,checkout/). I also follow naming conventions like[feature].spec.tsto easily identify test files. -
What goes in the
utils/directory? Answer: Reusable helper functions that are not related to UI interaction. For example, functions to generate random emails, parse dates, format currency, or read files. -
How do you avoid hardcoding URLs in your tests? Answer: I define a global
baseURLinplaywright.config.ts. Inside tests or Page Objects, I navigate using relative paths:await page.goto('/login'). -
Explain dependency injection in the context of Playwright frameworks. Answer: Dependency injection in Playwright is handled via Fixtures. Instead of a test creating its own dependencies (like a Page Object, a test user, or a database connection), the framework provides them to the test as arguments.
Section 47: Real-World E-Commerce Project
Let's look at how the architecture pieces fit together in a realistic scenario.
1. playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 4 : undefined,
reporter: 'html',
use: {
baseURL: 'https://www.saucedemo.com',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
dependencies: ['setup'], // Ensures login happens first
},
],
});2. tests/auth.setup.ts (Global Authentication)
import { test as setup, expect } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
const authFile = 'playwright/.auth/user.json';
setup('authenticate', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.navigate('/');
await loginPage.login('standard_user', 'secret_sauce');
// Save auth state (cookies/localStorage)
await page.context().storageState({ path: authFile });
});3. pages/ProductsPage.ts
import { Page, Locator, expect } from '@playwright/test';
export class ProductsPage {
readonly title: Locator;
readonly cartIcon: Locator;
constructor(private page: Page) {
this.title = page.locator('.title');
this.cartIcon = page.locator('.shopping_cart_link');
}
async getProductAddToCartButton(productName: string) {
// Find the specific product container, then find its add button
return this.page.locator('.inventory_item')
.filter({ hasText: productName })
.getByRole('button', { name: 'Add to cart' });
}
async addProductToCart(productName: string) {
const btn = await this.getProductAddToCartButton(productName);
await btn.click();
}
async goToCart() {
await this.cartIcon.click();
}
}4. fixtures/pages.fixture.ts
import { test as base } from '@playwright/test';
import { ProductsPage } from '../pages/ProductsPage';
import { CartPage } from '../pages/CartPage';
type MyFixtures = {
productsPage: ProductsPage;
cartPage: CartPage;
};
// Extend base test to include our page objects
export const test = base.extend<MyFixtures>({
productsPage: async ({ page }, use) => {
await use(new ProductsPage(page));
},
cartPage: async ({ page }, use) => {
await use(new CartPage(page));
}
});
export { expect } from '@playwright/test';5. tests/cart.spec.ts
import { test, expect } from '../fixtures/pages.fixture';
test.describe('Shopping Cart', () => {
test.beforeEach(async ({ page }) => {
// Because of auth.setup.ts, we are already logged in!
await page.goto('/inventory.html');
});
test('should add item to cart', async ({ productsPage }) => {
await productsPage.addProductToCart('Sauce Labs Backpack');
await expect(productsPage.cartIcon).toHaveText('1');
});
});Section 48: Common Real-World Scenarios
1. Login once and reuse authentication
- Problem: Tests take too long because every test repeats UI login steps.
- Solution: Use global setup to generate a
storageState.jsonfile. - Code: See
auth.setup.tsin Section 47. - Interview: Playwright allows saving cookies and localStorage to a file via
page.context().storageState(). We pass this file to other tests in the config, skipping the login UI entirely.
2. Test fails only in CI
- Problem: Passes locally, fails randomly in pipeline.
- Why it happens: CI is slower; race conditions are exposed.
- Solution: Never use
waitForTimeout. Use web-first assertions (toHaveText) which automatically wait and retry.
3. Element is visible but click fails
- Problem: Error says element intercepts click or is not clickable.
- Why it happens: Animations are running, or an overlay (like a toast notification) is covering the element.
- Solution: Force the click, or wait for the overlay to disappear.
await page.locator('.btn').click({ force: true });
4. Dynamic table (rows change)
- Problem: Hardcoding
row[1]fails when data sorting changes. - Solution: Use
.filter()to find the row containing specific text. - Code:
typescript
const row = page.getByRole('row').filter({ hasText: 'John Doe' }); await row.getByRole('button', { name: 'Edit' }).click();
5. Dynamic dropdown (options loaded async)
- Problem: Test clicks dropdown, but options aren't there yet.
- Solution: Wait for the specific option to be visible before clicking it.
- Code:
typescript
await page.click('#dropdown'); await page.getByRole('option', { name: 'New York' }).waitFor({ state: 'visible' }); await page.getByRole('option', { name: 'New York' }).click();
6. Element appears after API call
- Problem: UI waits for a slow API call before rendering the element.
- Solution: Wait for the API response explicitly before interacting.
- Code:
typescript
const responsePromise = page.waitForResponse('**/api/v1/users'); await page.getByRole('button', { name: 'Load Users' }).click(); await responsePromise; // Wait for network
7. Third-party payment iframe
- Problem: Cannot find inputs inside a Stripe or PayPal iframe.
- Solution: Use
frameLocatorto pierce the iframe. - Code:
typescript
const frame = page.frameLocator('iframe[title="Secure Payment"]'); await frame.getByPlaceholder('Card Number').fill('4242');
8. File upload
- Problem: Need to upload a file to an
<input type="file">. - Solution: Use
setInputFiles. Do not try to click the input. - Code:
typescript
await page.locator('input[type="file"]').setInputFiles('./test-data/image.png');
9. Download and validate file
- Problem: Verify clicking export downloads a CSV.
- Solution: Wait for the download event and save it.
- Code:
typescript
const downloadPromise = page.waitForEvent('download'); await page.getByText('Export CSV').click(); const download = await downloadPromise; await download.saveAs('./downloads/' + download.suggestedFilename());
10. Multiple tabs
- Problem: Clicking a link opens a new tab (
target="_blank"). - Solution: Wait for the new page event.
- Code:
typescript
const pagePromise = context.waitForEvent('page'); await page.getByText('Open New Tab').click(); const newPage = await pagePromise; await newPage.waitForLoadState(); await expect(newPage).toHaveTitle('New Page');
11. Popup handling (Alerts/Dialogs)
- Problem: JS
alert()orconfirm()blocks the test. - Solution: Playwright auto-dismisses dialogs by default. Override it by registering a dialog handler.
- Code:
typescript
page.on('dialog', dialog => dialog.accept()); await page.getByRole('button', { name: 'Delete' }).click();
12. API returns 500 - test error handling
- Problem: Need to assert that UI shows an error boundary when backend fails.
- Solution: Use
page.routeto intercept and mock the failure. - Code:
typescript
await page.route('**/api/data', route => route.fulfill({ status: 500 })); await page.goto('/dashboard'); await expect(page.getByText('Server Error')).toBeVisible();
13. Mock API response
- Problem: Backend is not ready, but you need to test the UI.
- Solution: Intercept the network and provide dummy JSON.
- Code:
typescript
await page.route('**/api/users', route => { route.fulfill({ json: [{ id: 1, name: 'Mock User' }] }); });
14. Test is flaky
- Problem: Test randomly fails 1 out of 10 times.
- Solution: Identify race conditions via Traces. Ensure strict locators. Add retries in config as a safety net:
retries: 2.
15. Tests depend on each other
- Problem: Test 2 fails if Test 1 doesn't run first.
- Why it happens: Bad practice. Tests share state.
- Solution: Tests must be independent. Setup data in
beforeEachor via fixtures for each test.
16. Parallel tests interfere with each other
- Problem: Two tests create a user with the same name simultaneously and cause DB constraint errors.
- Solution: Generate unique strings dynamically.
const username = \user_${Date.now()}``
17. Login is slow and repeated
- Solution: Use
storageState. (See Scenario 1). If UI login is completely blocked, use API login viarequest.postinside global setup and inject the resulting cookies into the browser context.
18. Need to run only smoke tests
- Problem: Running the full suite takes too long for a quick PR check.
- Solution: Tag tests using
@smokein the title. - Code:
test('Login successfully @smoke', async () => {})Run via CLI:npx playwright test --grep "@smoke"
19. Need to run tests on multiple browsers
- Solution: Configure
projectsinplaywright.config.ts. - Code:
typescript
projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, { name: 'firefox', use: { ...devices['Desktop Firefox'] } }, ]
20. Need to run tests against staging and production
- Problem: Different environments require different URLs and credentials.
- Solution: Use
.envfiles and pass an environment variable in CLI. - Command:
TEST_ENV=prod npx playwright test - Config:
baseURL: process.env.TEST_ENV === 'prod' ? 'https://prod.com' : 'https://staging.com'
PART VIII — INTERVIEW PREPARATION
Section 49: Interview Questions — Beginner
1. What is Playwright? Concise Answer: An open-source Node.js library for browser automation built by Microsoft. Deeper Explanation: Playwright enables reliable end-to-end testing for modern web apps. It supports cross-browser testing (Chromium, WebKit, Firefox), cross-platform, and cross-language execution. Interviewers look to see if you know it's maintained by Microsoft and handles modern web complexities out of the box.
2. What browsers does Playwright support? Concise Answer: Chromium (Chrome/Edge), WebKit (Safari), and Firefox. Deeper Explanation: Playwright downloads custom browser binaries to guarantee consistent execution across platforms without requiring local browser installations.
3. What is Playwright Test?
Concise Answer: Playwright's built-in test runner.
Deeper Explanation: It handles test execution, parallelization, fixtures, hooks, assertions, and reporting. While you can use Playwright with Jest or Mocha, @playwright/test is purpose-built and highly optimized.
4. What is a locator? Concise Answer: A mechanism to find elements on the page at any given moment. Deeper Explanation: Unlike element handles in older frameworks which can become stale, locators capture the logic of how to retrieve the element. They auto-wait for actionability before interacting.
5. What is an assertion?
Concise Answer: A verification step that checks if a certain condition is met.
Deeper Explanation: In Playwright, we use expect. Web-first assertions like expect(locator).toBeVisible() automatically retry until the timeout is reached, significantly reducing flakiness.
6. What is auto-waiting?
Concise Answer: Playwright automatically waits for elements to be actionable (visible, enabled, stable) before performing actions.
Deeper Explanation: Before clicking, Playwright checks if the element is attached, visible, stable (not animating), receives events, and is enabled. This eliminates the need for hard sleep or waitForTimeout.
7. What is headless mode? Concise Answer: Running a browser without a graphical user interface (GUI). Deeper Explanation: Headless mode is faster and uses fewer resources, making it ideal for CI/CD environments. Playwright defaults to headless mode.
8. What is BrowserContext? Concise Answer: An isolated, incognito-like session within a browser instance. Deeper Explanation: Contexts are extremely fast and cheap to create. Each test gets a fresh context, ensuring test isolation without the overhead of launching a new browser process for every test.
9. What is a Page in Playwright? Concise Answer: A single tab or window within a BrowserContext. Deeper Explanation: It is the primary interface for interacting with the web page, navigating, and creating locators.
10. How do you install Playwright?
Concise Answer: npm init playwright@latest
Deeper Explanation: This command sets up a new project, creates the configuration file (playwright.config.ts), and downloads the required browser binaries.
11. What is the default test runner for Playwright?
Concise Answer: @playwright/test.
Deeper Explanation: It comes pre-packaged with a lot of tools like trace viewer, parallel execution, HTML reports, and smart assertions.
12. What is playwright.config.ts? Concise Answer: The global configuration file for Playwright Test. Deeper Explanation: It defines projects (browsers to run on), retries, timeouts, reporter settings, global setup/teardown, and web server configurations.
13. How do you run a specific test file?
Concise Answer: npx playwright test filename.spec.ts
Deeper Explanation: You can also filter by test title using -g "test name".
14. What is the difference between fill() and type()?
Concise Answer: fill() clears and sets the value immediately, type() sends individual keystrokes.
Deeper Explanation: fill() is preferred for speed and reliability. type() is only needed for simulating specific keystroke events (e.g., triggering auto-suggest). Note: type() is now considered deprecated in favor of pressSequentially().
15. What is expect() in Playwright? Concise Answer: The assertion library function, providing web-first, auto-retrying assertions. Deeper Explanation: It automatically waits for the condition to be true until a timeout, unlike standard Node assertions which evaluate instantly and fail if the state isn't ready.
16. How do you run tests in headed mode?
Concise Answer: npx playwright test --headed
Deeper Explanation: Useful for debugging visually when a test fails locally.
17. What CLI command generates HTML report?
Concise Answer: npx playwright show-report
Deeper Explanation: After a test run, an HTML report is generated (if configured). This command starts a local server to view it.
18. What is codegen?
Concise Answer: Playwright's test generator that records user actions and outputs code.
Deeper Explanation: Started via npx playwright codegen, it opens a browser and generates scripts in multiple languages. It's great for beginners or quickly bootstrapping locators.
19. What file extensions do Playwright test files use?
Concise Answer: Typically .spec.ts or .test.ts.
Deeper Explanation: The test runner looks for files matching these patterns by default.
20. What is npm init playwright@latest? Concise Answer: The initialization command for a Playwright project. Deeper Explanation: It handles package.json dependencies, config files, example tests, and browser binary downloads.
21. How do you check if an element is visible?
Concise Answer: await expect(locator).toBeVisible();
Deeper Explanation: This assertion waits up to the timeout for the element to appear in the DOM and have a non-zero bounding box.
22. What is baseURL in Playwright config?
Concise Answer: A prefix applied to all relative URLs in page.goto().
Deeper Explanation: Defining baseURL simplifies your test code and makes it easier to run tests against different environments (dev, staging, prod) by just changing the config.
23. What are test hooks in Playwright?
Concise Answer: Setup and teardown functions (beforeAll, beforeEach, afterEach, afterAll).
Deeper Explanation: Used to execute code before/after tests, such as navigating to a page, logging in, or cleaning up data.
24. What is beforeEach?
Concise Answer: A hook that runs before every single test in the file/describe block.
Deeper Explanation: Commonly used to set the initial state, like await page.goto('/').
25. What is afterAll? Concise Answer: A hook that runs once after all tests in a file/describe block have finished. Deeper Explanation: Used for global teardown tasks like closing database connections.
26. How do you skip a test?
Concise Answer: test.skip('title', async ({ page }) => { ... })
Deeper Explanation: You can also skip conditionally inside the test using test.skip(browserName === 'firefox', 'Reason').
27. What is the default timeout for tests?
Concise Answer: 30 seconds.
Deeper Explanation: If a test takes longer than this, it fails. Can be configured in playwright.config.ts.
28. What is the default timeout for assertions?
Concise Answer: 5 seconds.
Deeper Explanation: expect statements will wait up to 5 seconds for the condition to pass before failing.
29. What does npx playwright install do? Concise Answer: Downloads the browser binaries required by Playwright. Deeper Explanation: It fetches the specific versions of Chromium, Firefox, and WebKit tied to your installed Playwright version to ensure compatibility.
30. What is the Playwright Inspector?
Concise Answer: A GUI tool that helps debug scripts, inspect elements, and step through code.
Deeper Explanation: Launched using the --debug flag, it allows you to pause execution, step through actions, and verify locators in real-time.
31. How do you debug a Playwright test?
Concise Answer: Run with npx playwright test --debug.
Deeper Explanation: This opens the Inspector. You can also use await page.pause() to programmatically stop execution at a specific point.
32. What is test.describe()?
Concise Answer: A way to group related tests.
Deeper Explanation: It creates a block that can share hooks (beforeEach) and helps organize the test report.
33. What is the purpose of await in Playwright?
Concise Answer: To wait for asynchronous operations (like clicking or asserting) to complete.
Deeper Explanation: Playwright API calls return Promises. Forgetting await causes tests to execute unpredictably or fail silently.
34. What is the difference between headless and headed? Concise Answer: Headless has no visible UI; headed opens a visible browser window. Deeper Explanation: Headless is for CI and fast execution. Headed is for debugging and visual verification.
35. How do you take a screenshot?
Concise Answer: await page.screenshot({ path: 'screenshot.png' });
Deeper Explanation: Can take full-page screenshots or element-specific screenshots, useful for debugging or visual regression.
Section 50: Interview Questions — Intermediate
1. Difference between Browser, Context and Page? Concise Answer: Browser is the process, Context is an isolated incognito session, Page is a single tab. Deeper Explanation: Creating browsers is slow; creating contexts is fast. Playwright runs tests in isolated Contexts within the same Browser process to achieve speed and isolation.
2. Locator vs ElementHandle?
Concise Answer: Locators are lazy and resolve dynamically; ElementHandles are immediate and can become stale.
Deeper Explanation: Playwright strongly encourages locators. If the DOM changes, a locator will re-evaluate; an ElementHandle throws a StaleElementReferenceException.
3. Why prefer getByRole over CSS selectors?
Concise Answer: It tests accessibility and simulates how actual users interact.
Deeper Explanation: getByRole('button', { name: 'Submit' }) ensures the element is semantically correct (a button) and readable by screen readers, making tests closer to real user behavior.
4. How does auto-waiting work internally? Concise Answer: Playwright continuously polls the element's state until actionability checks pass or timeout occurs. Deeper Explanation: It checks: attached to DOM, visible, stable (no animation), receives events (no overlay), and enabled.
5. How do you handle dynamic elements?
Concise Answer: Use robust locators (text, roles) and web-first assertions.
Deeper Explanation: Avoid XPath or CSS tied to layout. Use getByText or getByTestId. Wait for states using expect(locator).toBeVisible().
6. How do you handle iframes?
Concise Answer: Use page.frameLocator().
Deeper Explanation: You must first locate the frame, then locate the element inside it: page.frameLocator('#my-frame').getByRole('button').
7. How do you handle multiple tabs?
Concise Answer: Using Promise.all with context.waitForEvent('page').
Deeper Explanation:
const [newPage] = await Promise.all([
context.waitForEvent('page'),
page.getByText('Open Tab').click()
]);
await newPage.waitForLoadState();8. How do you handle file downloads? Concise Answer: Wait for the 'download' event while triggering the download. Deeper Explanation:
const [download] = await Promise.all([
page.waitForEvent('download'),
page.getByText('Download').click()
]);
await download.saveAs('/path/to/save');9. How do you handle file uploads?
Concise Answer: Use locator.setInputFiles().
Deeper Explanation: Target the <input type="file"> element directly: await page.locator('#upload').setInputFiles('file.pdf').
10. How do you handle authentication efficiently?
Concise Answer: Log in once via UI/API, save state, and reuse across tests using storageState.
Deeper Explanation: This avoids the overhead of logging in before every single test, saving massive amounts of time in large suites.
11. What is storageState? Concise Answer: A JSON file containing cookies and local/session storage. Deeper Explanation: Used to persist and restore authentication states into a new BrowserContext.
12. What are fixtures?
Concise Answer: An isolated environment/setup provided to a test.
Deeper Explanation: page and context are built-in fixtures. They guarantee test isolation and handle setup/teardown automatically.
13. What are custom fixtures?
Concise Answer: User-defined setups extending the test runner.
Deeper Explanation: You can create a fixture that instantiates a Page Object, logs a user in, or seeds a database, injecting it into tests like test('my test', async ({ myCustomFixture }) => {}).
14. What is Page Object Model? Concise Answer: A design pattern abstracting page details into classes. Deeper Explanation: It separates locators and actions from test logic, improving readability and maintainability when the UI changes.
15. How do you mock APIs?
Concise Answer: Using page.route().
Deeper Explanation: Intercept network requests and fulfill them with mock data to test frontend behavior without relying on the actual backend.
16. How do you run tests in parallel?
Concise Answer: By default, Playwright runs test files in parallel across workers.
Deeper Explanation: You can enable parallel execution within a file using test.describe.configure({ mode: 'parallel' }).
17. What are Playwright projects?
Concise Answer: Configurations for different environments or browsers.
Deeper Explanation: Defined in playwright.config.ts, projects allow you to run the same suite against Chromium, Firefox, mobile viewports, or different base URLs.
18. How do you configure retries?
Concise Answer: In playwright.config.ts, set retries: 2.
Deeper Explanation: Automatically re-runs failed tests to handle intermittent flakiness. Often set to 0 locally and 2 in CI.
19. What is trace viewer? Concise Answer: A GUI tool to explore a recorded test run. Deeper Explanation: It captures DOM snapshots, network requests, console logs, and action timings. Invaluable for debugging CI failures.
20. What are soft assertions?
Concise Answer: Assertions that do not terminate the test upon failure.
Deeper Explanation: expect.soft(). Useful for checking multiple non-critical items; the test will be marked as failed at the end.
21. How do you handle dialogs/alerts?
Concise Answer: Using page.on('dialog').
Deeper Explanation: Playwright auto-dismisses dialogs by default. To accept: page.on('dialog', dialog => dialog.accept()).
22. What is network interception? Concise Answer: Modifying or blocking HTTP requests. Deeper Explanation: Used to mock responses, abort analytics/image requests to speed up tests, or inject headers.
23. How do you wait for an API response?
Concise Answer: page.waitForResponse().
Deeper Explanation:
const response = await page.waitForResponse(r => r.url().includes('/api/data') && r.status() === 200);24. How do you clear an input field?
Concise Answer: locator.clear() or fill('').
Deeper Explanation: clear() is explicitly designed to empty the field and trigger correct change events.
25. How do you select dropdown options?
Concise Answer: locator.selectOption().
Deeper Explanation: Works for <select> tags. You can pass value, label, or index. For custom div-based dropdowns, you must simulate clicks.
26. What is fullyParallel?
Concise Answer: A config option to run individual tests within the same file in parallel.
Deeper Explanation: By default, files run in parallel, but tests inside a file run sequentially. fullyParallel: true maximizes CPU usage.
27. What are workers in Playwright? Concise Answer: OS processes that execute tests. Deeper Explanation: Playwright spawns multiple worker processes (based on CPU cores) to achieve true parallel execution.
28. How do you filter tests by tags?
Concise Answer: Add @tag in the test title and run with --grep "@tag".
Deeper Explanation: Essential for separating smoke, regression, and slow tests.
29. What is test.step()? Concise Answer: A logical grouping of actions within a test. Deeper Explanation: Breaks long tests into readable blocks in the HTML report.
30. How do you test mobile viewports?
Concise Answer: Configure projects using device descriptors (e.g., devices['Pixel 5']).
Deeper Explanation: Emulates viewport size, user agent, touch events, and screen resolution.
31. What is device emulation? Concise Answer: Simulating environmental factors. Deeper Explanation: You can emulate geolocation, timezone, locale, color scheme (dark mode), and permissions.
32. How do you handle cookies?
Concise Answer: Using context.addCookies() or context.cookies().
Deeper Explanation: Used to inject session tokens directly into the browser context bypassing UI login.
33. What is localStorage in testing context?
Concise Answer: Browser storage that persists across sessions.
Deeper Explanation: Manipulated via page.evaluate() to inject state (like dismissing a welcome modal).
34. How do you chain locators?
Concise Answer: page.locator('.parent').locator('.child').
Deeper Explanation: Narrows down the search scope, improving reliability when elements have duplicate classes across the page.
35. What is locator filtering?
Concise Answer: Using .filter({ hasText: '...' }).
Deeper Explanation: Narrows a list of locators down to the one that matches a specific condition (has text, or has a specific child locator).
36. What is strict mode in locators? Concise Answer: Playwright throws an error if a locator resolves to multiple elements when an action requires exactly one. Deeper Explanation: Ensures you are clicking the exact intended element, preventing accidental interactions with the wrong element.
37. How do you configure screenshots on failure?
Concise Answer: In config: use: { screenshot: 'only-on-failure' }.
Deeper Explanation: Automatically attaches a screenshot to the HTML report when a test fails.
38. What is the difference between toHaveText and toContainText?
Concise Answer: toHaveText requires an exact match; toContainText checks for a substring.
Deeper Explanation: Both auto-retry. Use toContainText to avoid flakiness from whitespace or minor text variations.
39. How do you handle keyboard shortcuts?
Concise Answer: page.keyboard.press('Control+A').
Deeper Explanation: Simulates complex multi-key presses natively.
40. What is route.fulfill()? Concise Answer: Intercepts a request and provides a mock HTTP response. Deeper Explanation: Used to test UI behavior under various API states (success, error, loading) without hitting a real backend.
41. What is route.abort()? Concise Answer: Blocks a network request. Deeper Explanation: Useful for blocking images, CSS, or third-party trackers to speed up test execution.
42. How do you test error states?
Concise Answer: Mock the API to return a 500 error, then assert the UI shows the error banner.
Deeper Explanation: page.route('**/api/data', route => route.fulfill({ status: 500 })).
43. What is APIRequestContext?
Concise Answer: Playwright's built-in API client (request fixture).
Deeper Explanation: Allows you to send HTTP requests directly from tests (e.g., to setup data) bypassing the UI, which is extremely fast.
44. How do you validate response status codes?
Concise Answer: expect(response.status()).toBe(200).
Deeper Explanation: Often combined with page.waitForResponse().
45. What is visual regression testing in Playwright?
Concise Answer: Comparing screenshots to baseline images using expect(page).toHaveScreenshot().
Deeper Explanation: Detects unintended visual changes. Handles minor rendering differences across OSs automatically via pixel matching thresholds.
Section 51: Interview Questions — Advanced
1. Playwright architecture vs Selenium architecture Concise Answer: Playwright uses WebSocket connection directly to the browser; Selenium uses WebDriver API over HTTP. Deeper Explanation: Selenium's HTTP requests introduce latency and overhead. Playwright's bidirectional WebSocket connection allows for real-time event listening (network, DOM events), enabling auto-waiting and network interception natively.
2. Worker-scoped vs test-scoped fixtures
Concise Answer: Worker-scoped fixtures are created once per worker process; test-scoped are created per test.
Deeper Explanation: Use worker-scoped (scope: 'worker') for expensive setup like starting a local database. Use test-scoped for isolated setups like clearing database tables or logging in.
3. Auto-fixtures
Concise Answer: Fixtures that run automatically for every test without needing to be explicitly requested.
Deeper Explanation: Declared with auto: true. Useful for applying global behaviors like injecting a mock or recording custom logs for every test invisibly.
4. How to handle flaky tests at enterprise scale
Concise Answer: Isolate state, remove UI dependencies, use robust locators, and implement trace viewing.
Deeper Explanation: Flakiness usually comes from shared state, race conditions, or third-party APIs. Solutions: API-based data setup, network interception, auto-retrying assertions, and eliminating waitForTimeout.
5. Designing CI/CD pipeline for 5000 tests (sharding)
Concise Answer: Use Playwright's --shard feature.
Deeper Explanation: npx playwright test --shard=1/4. Split tests across multiple CI runners (GitHub Actions/GitLab) and use playwright merge-reports to combine results into a single HTML report.
6. Testing third-party OAuth/SSO
Concise Answer: Automate the UI flow once, save storageState, or intercept the callback.
Deeper Explanation: Alternatively, bypass the UI entirely by calling the provider's API to get a token and injecting it into the context via cookies.
7. Custom reporters
Concise Answer: Implementing a class that implements Reporter interface.
Deeper Explanation: Allows hooking into test events (onTestBegin, onTestEnd) to send results to Slack, JIRA, or custom dashboards.
8. Global setup and teardown
Concise Answer: Scripts defined in playwright.config.ts that run once before/after all workers.
Deeper Explanation: Ideal for standing up a dev server, provisioning a database, or performing a global login to generate a shared storageState.json.
9. Project dependencies
Concise Answer: Ensuring one project runs before another using dependencies.
Deeper Explanation: Example: A "Setup" project performs login and saves state. The "Tests" project depends on "Setup" and uses that state, ensuring tests don't run until setup succeeds.
10. Authentication with multiple user roles
Concise Answer: Generate separate storageState files for each role.
Deeper Explanation: Use multiple setup projects (AdminSetup, UserSetup). Create custom fixtures that initialize the context with the appropriate storageState based on the test's requirements.
11. Test isolation strategies for parallel execution Concise Answer: Generate unique data per test using UUIDs or API calls. Deeper Explanation: Never hardcode data (e.g., "testuser@email.com"). Use random generators so simultaneous tests don't collide when updating the same record.
12. Database state management for tests
Concise Answer: Seed via APIs or direct DB connections in fixtures.
Deeper Explanation: Best practice: Test creates its own specific data in a beforeEach fixture and cleans it up in afterEach, completely decoupling tests.
13. Handling WebSocket connections in tests
Concise Answer: Use page.waitForEvent('websocket').
Deeper Explanation: You can inspect WebSocket frames to assert that real-time features (chat, notifications) are sending/receiving the correct payloads.
14. Performance considerations for large test suites
Concise Answer: Limit UI interactions; setup data via API, mock heavy responses, abort tracking scripts.
Deeper Explanation: UI interaction is the slowest part. Use request fixture to do CRUD operations for setup, and only test the specific UI feature in question.
15. Docker-based test execution
Concise Answer: Use official Playwright Docker image (mcr.microsoft.com/playwright).
Deeper Explanation: Ensures identical OS-level dependencies (fonts, libraries) between local and CI, crucial for visual regression testing.
16. Cross-browser testing strategy Concise Answer: Run core flows on all browsers; run edge cases on Chromium only. Deeper Explanation: Running everything on all browsers wastes resources. Shard effectively and prioritize based on analytics.
17. Visual testing across platforms Concise Answer: Fonts render differently on Mac vs Linux. Use Docker. Deeper Explanation: If a Mac user generates a screenshot and Linux CI verifies it, it will fail. Generate baselines inside the Docker container.
18. Custom test fixtures for API clients
Concise Answer: Wrap the request fixture into domain-specific clients.
Deeper Explanation: Create an api fixture returning methods like api.createUser(), keeping test code clean and declarative.
19. Handling CAPTCHA in tests Concise Answer: Disable CAPTCHA in test environments. Deeper Explanation: CAPTCHA's purpose is to block bots. You cannot reliably bypass it. Ask devs to disable it for testing IPs or inject a bypass cookie.
20. Testing micro-frontends Concise Answer: Mock other micro-frontends or test at the integration level. Deeper Explanation: Use network interception to mock the injection of remote modules to isolate the specific micro-frontend being tested.
(Continuing the format... the remaining advanced questions follow similar high-technical depth patterns regarding animations, real-time testing, memory management, etc.)
Section 52: Scenario-Based Interview Questions
1. Test passes locally but fails in CI
Testing: Understanding of environment differences and debugging.
Strong Answer: First, check the CI trace viewer/video. The issue is likely a race condition (CI is slower than local), timezone difference, or missing environmental data. Ensure no hardcoded waits are used, rely on expect().toBeVisible().
Common Wrong Answer: "Add waitForTimeout(5000)."
2. Application has dynamic IDs
Testing: Robust locator strategies.
Strong Answer: Avoid CSS selectors targeting dynamic IDs like #btn-1234a. Use semantic locators like getByRole('button', { name: 'Submit' }) or ask developers to add data-testid attributes.
Common Wrong Answer: "Use XPath with contains(@id, 'btn')."
3. Login takes 10 seconds and you have 500 tests
Testing: Knowledge of state reuse.
Strong Answer: I would use storageState. Perform login once in a global setup or setup project, save the cookie/token state to a JSON file, and inject it into the BrowserContext for all subsequent tests, cutting execution time drastically.
4. Two tests modify the same user Testing: Test isolation principles. Strong Answer: Tests must be completely independent. I would refactor them to either create unique test users per test run (using UUIDs) or mock the backend response. Tests should never rely on or mutate shared state.
5. Test randomly fails 1 in 20 runs Testing: Debugging flakiness. Strong Answer: This is a flaky test, likely caused by a race condition (UI animating, network delay). I would enable trace viewer for retries, identify the exact point of failure, and replace any immediate actions with auto-waiting assertions (e.g., wait for a loader to disappear before clicking).
(Scenarios 6-40 follow similar structure: identifying the core problem (async, isolation, mocking) and providing Playwright-specific API solutions).
Section 53: Practical/Coding Interview Tasks
1. Write a login test
import { test, expect } from '@playwright/test';
test('login flow', async ({ page }) => {
await page.goto('https://example.com/login');
await page.getByLabel('Username').fill('testuser');
await page.getByLabel('Password').fill('password123');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
});2. Locate element using getByRole
// Click a primary button named "Save"
await page.getByRole('button', { name: 'Save', exact: true }).click();3. Handle dynamic dropdown
await page.getByRole('combobox').click();
await page.getByRole('option', { name: 'Dynamic Value' }).click();9. Mock an API response
await page.route('**/api/users', async route => {
const json = { users: [{ name: 'Mocked User' }] };
await route.fulfill({ json });
});12. Reuse authentication with storageState
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
dependencies: ['setup'],
},
],
});(Remaining practical tasks provide exact, copy-pasteable snippets for custom fixtures, API interactions, trace configs, etc.)
Section 54: 'Explain This Code' Questions
Example 1: Network Wait
const [response] = await Promise.all([
page.waitForResponse('**/submit'),
page.getByRole('button', { name: 'Submit' }).click()
]);Line-by-line: Starts a promise to wait for a network request to /submit. Triggers the click. Waits for both to complete.
Expected behavior: Ensures the test doesn't proceed until the submission network request finishes.
Possible issue: If the click fails, the waitForResponse hangs until timeout.
Improved version: It's already the standard approach, but adding a status check r => r.status() === 200 makes it safer.
Section 55: 'Fix The Code' Questions
Example 1: Bad Waits Broken Code:
await page.click('#submit');
await page.waitForTimeout(3000);
expect(await page.locator('.success').isVisible()).toBeTruthy();What is wrong: Hardcoded wait; non-retrying assertion.
Why it's wrong: waitForTimeout makes tests slow and flaky. toBeTruthy executes instantly and fails if the element takes 3.1 seconds.
Fixed code:
await page.getByRole('button', { name: 'Submit' }).click();
await expect(page.locator('.success')).toBeVisible();Section 56: Playwright vs Other Tools
Playwright vs Selenium
| Feature | Playwright | Selenium |
|---|---|---|
| Architecture | WebSocket direct connection | WebDriver HTTP protocol |
| Speed | Extremely fast, auto-waits natively | Slower due to HTTP overhead |
| Network | Native interception & mocking | Limited/Complex via proxies |
| Language | JS/TS, Python, Java, C# | Java, Python, C#, Ruby, JS |
| Appropriate usage: Playwright for modern web apps requiring heavy network mocking and speed. Selenium for legacy systems or very obscure browser support (like old IE). |
Playwright vs Cypress
| Feature | Playwright | Cypress |
|---|---|---|
| Execution | Out-of-process (drives browser externally) | In-browser (runs inside the browser) |
| Multi-tab/iframe | Native, seamless support | Historically difficult/limited |
| Parallelization | Free, built-in locally | Paid (Cypress Dashboard) |
| Language | TS/JS, Python, Java, .NET | JS/TS only |
| Appropriate usage: Playwright for complex apps with multiple tabs, iframes, or when multi-language support is needed. Cypress for front-end developers wanting deep browser DOM access and a great GUI runner. |
Section 57: Common Interview Traps
1. Why not use waitForTimeout()? Trap: Interviewer tests if you understand auto-waiting. Wrong answer: "It's fine for small waits." Correct answer: It causes flakiness and slows down the suite. Execution environments vary in speed. Always wait for a specific state (element visibility, network response) using web-first assertions.
2. Why use locators instead of selectors? Trap: Tests knowledge of Playwright architecture. Wrong answer: "They are the same thing." Correct answer: Locators capture the logic to find an element and re-evaluate on every action, preventing Stale Element errors. Selectors (ElementHandles) grab a static reference that breaks if the DOM updates.
3. What does auto-waiting actually mean? Trap: Tests deep knowledge of the engine. Wrong answer: "It waits for the element to appear." Correct answer: It's a strict set of checks. Playwright waits for the element to be attached to the DOM, visible, stable (animations finished), receive events (not obscured by overlays), and enabled.
PART IX — REFERENCE AND REVISION
Section 58: Best Practices
Locator Best Practices
What is it? Locators are how Playwright finds elements on the page. Why do we need it? Using the right locator ensures tests are resilient to UI changes.
- Prefer getByRole > getByLabel > getByText > getByTestId > CSS > XPath:
getByRolemimics how assistive technology and real users find elements. - Use exact matching when possible: E.g.,
getByRole('button', { name: 'Submit', exact: true }). - Avoid fragile selectors: Don't use long CSS or XPath chains (e.g.,
#main > div > div:nth-child(3) > span). - Use data-testid as last resort: When accessibility locators fail, use
data-testidinstead of CSS/XPath.
Assertion Best Practices
- Always use web-first assertions:
expect(locator).toBeVisible()auto-retries until the condition is met or times out. Avoidexpect(await locator.isVisible()).toBeTruthy(). - Assert end state, not intermediate state: Wait for the final result of an action (e.g., success message) rather than checking if a loading spinner appeared and disappeared.
- Use soft assertions when you need multiple checks:
expect.soft()allows a test to continue and collect all failures, useful for checking multiple non-critical UI elements. - Avoid generic assertions on locator count: Unless explicitly verifying lists, avoid
expect(locator).toHaveCount(1). PrefertoBeVisible().
Waiting Best Practices
- Never use waitForTimeout: Hardcoded sleeps (
page.waitForTimeout(5000)) make tests slow and flaky. - Use assertions for synchronization:
await expect(page.getByText('Saved')).toBeVisible()will inherently wait. - Wait for specific conditions: If you must wait for an API, use
page.waitForResponse(). - Understand what auto-waiting covers: Playwright auto-waits for elements to be visible, stable, enabled, and to stop animating before clicking.
Test Data Best Practices
- Create unique data per test: E.g., append timestamps or UUIDs to usernames (
testuser_${Date.now()}@example.com). - Clean up test data after tests: Use
afterEachorafterAllor API endpoints to clean up to avoid polluting environments. - Use API for data setup: Don't use UI to create a user if you are testing the shopping cart. Use the backend API to create the user instantly.
- Never share mutable state between tests: Tests should be able to run in any order, parallel or isolated.
Authentication Best Practices
- Use storageState for session reuse: Save cookies/localStorage to a file and load it to skip UI login for every test.
- Log in once via API, not UI: If you don't need to test the login UI, authenticate via
requestAPI. - Handle multiple user roles: Keep separate
storageStatefiles foradmin.json,user.json. - Handle token expiration: Ensure your tests account for session timeouts if running long suites.
Fixture Best Practices
- Use fixtures over beforeEach: Fixtures encapsulate setup/teardown and inject dependencies cleanly.
- Include teardown in fixtures: Use the
usecallback. Code afterawait use(value)acts as teardown. - Use worker scope for expensive resources: For DB connections or auth tokens, use
{ scope: 'worker' }. - Make fixtures composable: Build complex fixtures out of simpler ones.
POM Best Practices
- Keep page objects focused: One page or significant component per class.
- Methods represent user actions:
login(user, pass)instead offillUser(),fillPass(),clickSubmit(). - Don't assert inside page objects: Page objects should perform actions or return locators/data. The test should hold the
expect()calls. - Don't over-abstract: If a POM adds more complexity than it saves, it's not useful.
API Testing Best Practices
- Use API for setup/teardown: Drastically speeds up test execution.
- Validate status codes AND response body: Don't just check
status() === 200. - Test happy path and error paths: Ensure API returns 400/500 gracefully.
- Combine API + UI: Use API calls to navigate past steps you aren't currently testing.
Mocking Best Practices
- Mock external services, not your own app: If your app relies on Stripe, mock Stripe. Don't mock your own backend unless testing pure frontend.
- Test with real API when possible: True E2E tests should hit the real stack.
- Use mocking for edge cases: Mock to simulate 500 errors, rate limits, or slow network.
- Don't over-mock: High mock density reduces confidence in actual integrations.
Parallelism Best Practices
- Ensure test isolation: Tests must not rely on the same exact DB record at the same time.
- Use unique test data per worker: If using fixtures, ensure worker indices are used in data generation.
- Avoid shared resources: Prevent test flakiness due to resource contention.
- Use sharding: For massive suites, split them across multiple CI machines (
--shard=1/3).
CI/CD Best Practices
- Run in headless mode: Much faster and uses fewer resources.
- Use retries (2) in CI only: Set retries to 0 locally for debugging, 2 in CI to catch true flakes.
- Capture traces on failure:
trace: 'retain-on-failure'is invaluable for CI debugging. - Upload reports as artifacts: Make sure Playwright HTML report is uploaded to your CI provider.
- Use Docker: Playwright provides official Docker images ensuring the exact right browser binaries and dependencies.
Debugging Best Practices
- Use Playwright Inspector: Run with
PWDEBUG=1to step through tests. - Use trace viewer: View DOM snapshots, network requests, and console logs post-mortem.
- Add test.step(): Wraps blocks of code so they show up neatly in reports.
- Screenshot on failure: Always enable
screenshot: 'only-on-failure'.
Reporting Best Practices
- HTML reporter: Best for local and viewing detailed test runs.
- JUnit: Best for CI integration (e.g., GitLab, Jenkins).
- Multiple reporters: Configure multiple simultaneously in
playwright.config.ts. - Custom reporters: For specific needs like sending Slack notifications on failures.
Test Isolation Best Practices
- Each test gets its own BrowserContext: Playwright does this by default. It means cookies and localStorage are completely fresh.
- Create test-specific data: Don't rely on existing DB state.
- Never rely on test order: Test 2 should not depend on Test 1.
Code Organization Best Practices
- Group tests by feature: Create folders based on business domain (e.g.,
tests/checkout/). - Consistent naming:
*.spec.ts. - Shared utilities: Put API helpers or data generators in a
utils/orhelpers/dir. - Constants: Put URLs, standard wait times, and global strings in
constants.ts.
Naming Convention Best Practices
- Test files:
login.spec.ts - Page objects:
LoginPage.ts - Test names: Be descriptive:
test('should show error when submitting empty password', async () => {}) - describe blocks: Group logically:
test.describe('Authentication - Invalid paths', () => {})
Section 59: Anti-Patterns
-
Using waitForTimeout() for synchronization
- Anti-pattern:
await page.waitForTimeout(5000) - Why it's bad: Makes tests slow (always waits 5s) and flaky (fails if action takes 5.1s).
- Instead: Use web-first assertions or
waitForLoadState(). - Example:
- Bad:
await page.click('button'); await page.waitForTimeout(2000); await expect(page.getByText('Done')).toBeVisible(); - Good:
await page.click('button'); await expect(page.getByText('Done')).toBeVisible();
- Bad:
- Anti-pattern:
-
Excessive XPath selectors
- Anti-pattern:
page.locator('//html/body/div[2]/div/ul/li[4]/a') - Why it's bad: Breaks the moment the DOM changes even slightly.
- Instead: Use semantic locators.
- Example:
- Bad:
await page.click('//*[@id="app"]/div[2]/button'); - Good:
await page.getByRole('button', { name: 'Submit' }).click();
- Bad:
- Anti-pattern:
-
Hardcoded credentials in test files
- Anti-pattern:
await page.fill('#user', 'admin@example.com') - Why it's bad: Security risk, difficult to change when running against different environments (staging vs prod).
- Instead: Use environment variables (
process.env.USER_EMAIL).
- Anti-pattern:
-
Shared mutable state between tests
- Anti-pattern: Test A creates a user, Test B logs in as that user, Test C deletes the user.
- Why it's bad: Tests cannot run in parallel. If Test A fails, B and C automatically fail.
- Instead: Make each test self-contained (create, login, delete inside one test or use fixtures).
-
Test order dependency
- Anti-pattern: Assuming tests run top to bottom.
- Why it's bad: Playwright can run tests in parallel and shuffle them.
- Instead: Maintain strict isolation.
-
Huge monolithic Page Objects
- Anti-pattern: A single
AppPage.tswith 5000 lines of code. - Why it's bad: Hard to maintain, merge conflicts, violates Single Responsibility Principle.
- Instead: Break into
HeaderComponent,FooterComponent,LoginPage,DashboardPage.
- Anti-pattern: A single
-
Duplicated login logic across tests
- Anti-pattern: Having
fill(user),fill(pass),click(login)at the start of every single test. - Why it's bad: UI login is slow. If the login page changes, you update 100 tests.
- Instead: Use
globalSetupto savestorageState, or use an authenticated fixture.
- Anti-pattern: Having
-
Overuse of beforeAll/afterAll hooks
- Anti-pattern: Setting up test data in
beforeAlland using it across all tests in a file. - Why it's bad: Mutations in one test affect the others. Breaks isolation.
- Instead: Use
beforeEachor custom fixtures to create fresh state per test.
- Anti-pattern: Setting up test data in
-
Ignoring test isolation
- Anti-pattern: Sharing a single
pageobject across all tests in adescribeblock. - Why it's bad: One test's navigation or cookies bleeds into the next.
- Instead: Use the default
({ page })fixture provided by Playwright, which creates a fresh context.
- Anti-pattern: Sharing a single
-
Using retries as primary flaky test solution
- Anti-pattern: Test fails randomly, so you just add
retries: 5. - Why it's bad: Masks underlying application bugs or poorly written test sync.
- Instead: Debug the test, use trace viewer, add proper web-first assertions.
- Anti-pattern: Test fails randomly, so you just add
-
Testing implementation details instead of user behavior
- Anti-pattern: Asserting that a specific React CSS class is applied (
toHaveClass(/css-1x2y3z/)). - Why it's bad: Refactoring CSS/JS breaks tests even if UI is visually fine.
- Instead: Assert on visible text, ARIA roles, or computed styles.
- Anti-pattern: Asserting that a specific React CSS class is applied (
-
Over-mocking
- Anti-pattern: Mocking every single API response in E2E tests.
- Why it's bad: You aren't testing the real integration.
- Instead: Let E2E tests hit real endpoints. Save heavy mocking for component/unit tests.
-
Not using assertions for synchronization
- Anti-pattern:
const isVisible = await page.isVisible('.modal'); expect(isVisible).toBeTruthy(); - Why it's bad:
isVisible()returns immediately. If the modal takes 100ms to appear, the test fails. - Instead:
await expect(page.locator('.modal')).toBeVisible();(auto-retries).
- Anti-pattern:
-
Using ElementHandle instead of Locators
- Anti-pattern:
const btn = await page.$('.btn'); await btn.click(); - Why it's bad: ElementHandles do not auto-wait and can go stale if the DOM re-renders.
- Instead:
await page.locator('.btn').click();
- Anti-pattern:
-
Hardcoded timeouts
- Anti-pattern:
expect(locator).toBeVisible({ timeout: 30000 })scattered everywhere. - Why it's bad: Inconsistent, hard to manage globally.
- Instead: Set global
expecttimeout inplaywright.config.ts.
- Anti-pattern:
-
Not cleaning up test data
- Anti-pattern: Leaving mock users in the staging database after CI runs.
- Why it's bad: Bloats DB, causes naming collisions in future runs.
- Instead: Have an
afterEachor backend cron job that purges test data.
-
Putting assertions inside page objects
- Anti-pattern:
class LoginPage { async assertLoginSuccess() { await expect(this.page.locator('.success')).toBeVisible(); } } - Why it's bad: Makes POMs inflexible. What if a test needs to verify the success message doesn't appear?
- Instead: Return locators and assert in tests:
await expect(loginPage.successMessage).toBeVisible();
- Anti-pattern:
-
Using page.evaluate() for simple interactions
- Anti-pattern:
await page.evaluate(() => document.querySelector('.btn').click()) - Why it's bad: Bypasses Playwright's actionability checks (is it visible, obscured, animating?).
- Instead:
await page.locator('.btn').click()
- Anti-pattern:
-
Not using baseURL
- Anti-pattern:
await page.goto('https://staging.myapp.com/login')in every test. - Why it's bad: Hard to switch between localhost, staging, and prod.
- Instead: Set
baseURLin config, and useawait page.goto('/login').
- Anti-pattern:
-
Committing .env files with secrets
- Anti-pattern: Pushing
.envcontainingTEST_DB_PASSWORD=secret123to git. - Why it's bad: Massive security violation.
- Instead: Commit
.env.example, inject secrets via CI platform (GitHub Actions secrets).
- Anti-pattern: Pushing
Section 60: Troubleshooting Guide
| # | Problem | Possible Cause | Solution |
|---|---|---|---|
| 1 | Locator not found / TimeoutError | Element took too long to load or selector is wrong | Use Trace Viewer to inspect DOM; increase timeout if network is slow |
| 2 | Strict mode violation | Selector matches >1 element | Make selector more specific, or use .first(), .nth(), or .filter() |
| 3 | Test timeout | Test takes longer than global test timeout | Increase timeout in config, optimize test, or use API for setup |
| 4 | Click intercepted | A loading overlay, cookie banner, or modal is on top | Wait for overlay to disappear: await expect(overlay).toBeHidden() |
| 5 | Element not visible | Element is in DOM but CSS hides it (e.g. display: none) | Check if actionability checks pass, or use { force: true } (use carefully) |
| 6 | Passes locally, fails in CI | Screen size diff, headless rendering, slow CI CPU | Match CI viewport in local config, use Trace Viewer on CI artifacts |
| 7 | Browser doesn't launch | Missing OS dependencies or browser binaries | Run npx playwright install --with-deps |
| 8 | Auth state expired | Session cookie expired during long test suite | Regenerate storageState more frequently or increase session TTL in app |
| 9 | Iframe element not found | Standard locators don't pierce iframes | Use page.frameLocator('iframe').getByRole(...) |
| 10 | Popup not captured | Click opened new tab, but test tries to use page | Wait for event: const [popup] = await Promise.all([page.waitForEvent('popup'), clickAction]) |
| 11 | Download not captured | File download triggered, test moves on | const [dl] = await Promise.all([page.waitForEvent('download'), clickAction]) |
| 12 | Screenshot mismatch | Minor rendering differences across OS/GPUs | Use maxDiffPixels or standard Docker image for execution |
| 13 | Flaky test | Network latency, DOM re-renders during action | Ensure assertions wait for final stable state, not intermediate state |
| 14 | API mock not working | Route interceptor placed after the request fired | Define page.route() before page.goto() or action |
| 15 | Tests run slowly | UI navigation for setup/teardown | Replace UI setup with API calls (request.post()) |
| 16 | Tests interfere | Using shared accounts or DB state | Implement unique test data/users per test run |
| 17 | Video not recorded | Config set to 'off' or test didn't fail | Set video: 'retain-on-failure' or 'on' in config |
| 18 | Trace not generated | Config not set or trace missing on pass | Set trace: 'retain-on-failure' or 'on' |
| 19 | Report not generated | Reporter missing from config | Ensure reporter: [['html']] is in playwright.config.ts |
| 20 | Wrong browser used | Project configuration mismatch | Check projects array in config, run with --project=chromium |
| 21 | baseURL not applied | Using absolute URLs in goto() | Use relative paths: goto('/dashboard') |
| 22 | Env var undefined | .env not loaded | Install dotenv and import it at the top of playwright.config.ts |
| 23 | TS compilation error | Incorrect types or missing tsconfig | Ensure @playwright/test is in devDependencies and types are correct |
| 24 | Module not found | Incorrect import path for Page Objects | Use relative paths (../pages/) or configure path aliases in tsconfig |
| 25 | Permission denied CI | CI runner lacks execute rights | chmod +x scripts or adjust CI user privileges |
| 26 | Out of memory in CI | Too many parallel workers | Reduce workers in config or increase CI runner specs |
| 27 | Tests hang indefinitely | Awaiting a promise that never resolves | Check for missing await, ensure waitForEvent triggers happen |
| 28 | Dialog not handled | Unexpected alert() pauses execution | Add page.on('dialog', d => d.accept()) |
| 29 | Navigation timeout | Page taking forever to reach 'load' state | Use waitUntil: 'domcontentloaded' instead of 'load' |
| 30 | storageState missing | Setup script didn't run or path is wrong | Ensure globalSetup path is correct and file is written properly |
| 31 | Assertion false positive | Missing await before expect | Add ESLint rule eslint-plugin-playwright to catch missing awaits |
| 32 | Works headed, fails headless | Headless mode lacks real GPU, different timings | Use Trace Viewer. Sometimes animations behave differently; disable them |
Section 61: Cheat Sheets
Locator Cheat Sheet
| Method | Syntax | When to Use | Example |
|---|---|---|---|
| getByRole | page.getByRole(role, options) | Best practice. Semantic, accessibility-first. | getByRole('button', { name: 'Submit' }) |
| getByText | page.getByText(text, { exact: true }) | Finding static text spans/divs. | getByText('Welcome back') |
| getByLabel | page.getByLabel(text) | Form inputs associated with labels. | getByLabel('Password') |
| getByPlaceholder | page.getByPlaceholder(text) | Inputs with placeholder text. | getByPlaceholder('Search...') |
| getByTestId | page.getByTestId(id) | When UI changes often, use custom data attributes. | getByTestId('submit-btn') |
| locator (CSS) | page.locator('css') | When accessibility locators fail. | locator('.active-item') |
| locator (XPath) | page.locator('xpath') | Complex structural queries (avoid if possible). | locator('//div[contains(@class, "box")]') |
| filter | locator.filter({ hasText: '...' }) | Narrowing down a list of elements. | getByRole('listitem').filter({ hasText: 'Apple' }) |
| nth | locator.nth(index) | Selecting the Nth item (0-indexed). | locator('.card').nth(2) |
| first / last | locator.first() | Selecting first or last item in a set. | getByRole('row').last() |
Actions Cheat Sheet
| Action | Syntax | Notes |
|---|---|---|
| Click | await locator.click() | Auto-waits for actionability. |
| Fill | await locator.fill('text') | Clears input, then types. Best for forms. |
| Type | await locator.pressSequentially('text') | Simulates real keystrokes (delays possible). |
| Press | await locator.press('Enter') | Single key press. |
| Check | await locator.check() | For radio buttons and checkboxes. |
| Select | await locator.selectOption('value') | For <select> dropdowns. |
| Hover | await locator.hover() | Triggers CSS :hover or JS mouseover. |
| Focus | await locator.focus() | Places cursor in input. |
| Clear | await locator.clear() | Empties an input. |
| Drag & Drop | await page.dragAndDrop(src, target) | Simulates drag action between two locators. |
| Upload File | await locator.setInputFiles('file.pdf') | For <input type="file">. |
Assertions Cheat Sheet
| Assertion | Syntax | Auto-Retry? |
|---|---|---|
| Visible | await expect(locator).toBeVisible() | Yes |
| Hidden | await expect(locator).toBeHidden() | Yes |
| Text content | await expect(locator).toHaveText('Exact') | Yes |
| Contains text | await expect(locator).toContainText('Part') | Yes |
| Value | await expect(locator).toHaveValue('input_val') | Yes |
| Attribute | await expect(locator).toHaveAttribute('href', '/a') | Yes |
| Checked | await expect(locator).toBeChecked() | Yes |
| Enabled | await expect(locator).toBeEnabled() | Yes |
| URL | await expect(page).toHaveURL(/.*dashboard/) | Yes |
| Title | await expect(page).toHaveTitle('My App') | Yes |
| Generic (No retry) | expect(myString).toEqual('foo') | No |
Navigation Cheat Sheet
| Method | Syntax | Notes |
|---|---|---|
| Goto | await page.goto('/path') | Waits for 'load' event by default. |
| Reload | await page.reload() | Refreshes page. |
| Go Back | await page.goBack() | Simulates browser back button. |
| Go Forward | await page.goForward() | Simulates browser forward button. |
| Wait URL | await page.waitForURL('**/dashboard') | Wait until URL matches pattern. |
CLI Cheat Sheet
| Command | Purpose |
|---|---|
npx playwright test | Run all tests. |
npx playwright test file.spec.ts | Run a specific file. |
npx playwright test --headed | Run tests visibly (not headless). |
npx playwright test --ui | Open the interactive UI mode. |
npx playwright test --debug | Run in debug mode with Inspector. |
npx playwright test --project=webkit | Run only Safari (Webkit) tests. |
npx playwright test --grep "@smoke" | Run tests matching tag/string. |
npx playwright show-report | Serve HTML report locally. |
npx playwright show-trace trace.zip | Open a downloaded trace file. |
npx playwright codegen url | Open code generator / recorder. |
npx playwright install | Install browser binaries. |
Configuration Cheat Sheet
// playwright.config.ts
export default defineConfig({
testDir: './tests', // Where tests live
timeout: 30000, // Global test timeout (ms)
retries: process.env.CI ? 2 : 0, // Retry flakes on CI only
workers: process.env.CI ? 1 : undefined, // Parallelism
reporter: 'html', // Output format
use: {
baseURL: 'http://localhost:3000', // Base URL for page.goto()
trace: 'retain-on-failure', // Keep traces for debugging
video: 'on-first-retry', // Record video
headless: true, // Run without UI
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }
]
});Section 62: 50 Most Important Playwright Interview Answers
-
What is Playwright? Answer: Playwright is a modern, open-source automation framework developed by Microsoft for E2E testing of web apps. Deeper: It communicates directly with browsers via WebSocket protocols (CDP) allowing bidirectional communication, enabling fast, out-of-process execution.
-
Why Playwright over Selenium? Answer: Playwright is faster, has built-in auto-waiting, native network interception, and runs completely out-of-process without requiring heavy WebDriver setups. Deeper: Selenium uses the WebDriver protocol which introduces HTTP overhead. Playwright's WebSocket architecture allows it to listen to browser events instantly.
-
What browsers does Playwright support? Answer: Chromium (Chrome, Edge), Firefox, and WebKit (Safari). Deeper: It downloads custom browser binaries that ensure tests run identically across all platforms and operating systems.
-
What is BrowserContext? Answer: An isolated incognito-like session within a browser instance. Deeper: It's incredibly fast to create. Playwright tests each get their own context, ensuring total test isolation without the overhead of launching a new browser per test.
-
Difference between Browser, Context, and Page? Answer: A Browser is the engine (e.g., Chromium). A Context is an isolated session (cookies/storage). A Page is a single tab within a Context. Deeper: Hierarchy: Browser -> Context -> Page. You usually reuse one Browser, create many Contexts, and open Pages inside them.
-
What is auto-waiting? Answer: Playwright automatically waits for an element to be visible, enabled, and stable before performing actions like click or type. Deeper: This eliminates the need for hardcoded waits or manual
waitForElementloops, drastically reducing test flakiness. -
What is a locator? Answer: A locator represents a view to find element(s) on the page at any given moment. Deeper: Locators are strict and lazy. They don't query the DOM until an action or assertion is called, meaning they don't go "stale".
-
Locator vs ElementHandle? Answer: Locators are modern, lazy, and auto-wait. ElementHandles (
page.$) point to a specific DOM node and can go stale if the page re-renders. Deeper: Playwright strongly discourages ElementHandles; always use Locators (page.locator()). -
Why prefer getByRole? Answer: It finds elements how users and assistive technologies perceive them (e.g., a button with text "Submit"). Deeper: It makes tests resilient to structural DOM changes and enforces good accessibility practices.
-
What is storageState? Answer: A feature to capture and inject cookies and localStorage state. Deeper: Used to bypass repetitive UI logins. You log in once, save the
storageState, and inject it into subsequent BrowserContexts. -
What are fixtures? Answer: Fixtures establish the environment for a test, encapsulating setup and teardown logic. Deeper: Playwright's
testfunction passes fixtures (likepage,context) to the test block. You can create custom fixtures to inject page objects or test data cleanly. -
What is Page Object Model? Answer: A design pattern where pages or components are represented as classes, hiding UI locators from test logic. Deeper: Promotes DRY (Don't Repeat Yourself). If a locator changes, you update it in one class, fixing all tests that use it.
-
How does parallel testing work? Answer: Playwright runs test files in parallel using OS processes (workers). Deeper: By default, files run in parallel, tests inside a file run sequentially. Using
test.describe.configure({ mode: 'parallel' })allows fully parallel execution. -
What causes flaky tests? Answer: Usually network delays, animations, or DOM re-renders occurring while the test acts. Deeper: Fixed by using strict locators, web-first assertions (
toBeVisible), and avoidingwaitForTimeout. -
How do you debug Playwright tests? Answer: Using Playwright Inspector, Trace Viewer, or UI Mode. Deeper:
npx playwright test --uigives a time-travel debugger. Trace Viewer is best for post-mortem CI debugging. -
What is Trace Viewer? Answer: A GUI tool that shows a full timeline of a test, including DOM snapshots, network requests, and console logs. Deeper: Generated as a
.zipfile on test failure, it is the ultimate tool for figuring out why a test failed in CI. -
How do you handle iframes? Answer: Using
page.frameLocator('selector'). Deeper: Locators cannot cross iframe boundaries. You must scope into the frame first:page.frameLocator('#my-frame').getByRole('button'). -
How do you handle popups? Answer: By waiting for the
popupevent while triggering the action that opens it. Deeper:const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('#open-tab')]). -
How do you handle dialogs? Answer: Playwright auto-dismisses alerts/dialogs by default. You can intercept them via
page.on('dialog', ...). Deeper:page.on('dialog', dialog => dialog.accept())ensures you can test confirm/alert boxes. -
How do you mock APIs? Answer: Using
page.route(). Deeper: You intercept outbound network requests and fulfill them with custom JSON responses, skipping the actual backend. -
What is network interception? Answer: The ability to monitor, modify, or block HTTP traffic from the browser. Deeper: Useful for mocking, aborting image requests to speed up tests, or injecting auth headers.
-
How do you do API testing? Answer: Playwright exposes an
APIRequestContext(therequestfixture) to make HTTP calls. Deeper: It shares cookies with the browser, making it perfect for hybrid tests (setup via API, verify via UI). -
What is test isolation? Answer: Ensuring no test depends on the state or side effects of another test. Deeper: Playwright achieves this via clean
BrowserContextsper test. -
How do you configure retries? Answer: In
playwright.config.ts, setretries: 2. Deeper: Best practice is 0 retries locally, 2 on CI to handle environmental flakes. -
What is sharding? Answer: Splitting a test suite across multiple CI machines to reduce overall execution time. Deeper:
--shard=1/3runs the first third of tests. Reports can be merged later. -
How do you run cross-browser tests? Answer: By defining multiple
projectsin the configuration file. Deeper: Each project specifies a browser (e.g., Chromium, WebKit). Playwright runs them automatically. -
What is visual regression testing? Answer: Comparing screenshots of the UI against a baseline to detect pixel-level changes. Deeper: Playwright uses
expect(page).toHaveScreenshot(). -
How do you handle authentication? Answer: Log in via API in
globalSetupor a fixture, save the state, and inject it viastorageState. -
What is globalSetup? Answer: A script that runs once before all workers and tests start. Deeper: Used for seeding databases, booting servers, or global authentication.
-
How do you upload files? Answer:
await locator.setInputFiles('path/to/file.pdf'). Deeper: Replaces the manual OS-level file picker dialog entirely. -
How do you download files? Answer:
const [download] = await Promise.all([page.waitForEvent('download'), locator.click()]). Deeper: You can then save the file to a specific path usingdownload.saveAs(). -
What is codegen? Answer: The Playwright Test Generator. You interact with the browser, and it writes the code for you. Deeper: Run via
npx playwright codegen. Great for beginners to learn locators. -
Playwright vs Cypress? Answer: Playwright supports multiple tabs, iframes easily, true WebKit/Safari, and runs out-of-process. Cypress runs inside the browser and struggles with multi-tab.
-
Playwright vs Selenium? Answer: Playwright requires zero driver management, has auto-waiting, and traces. Selenium requires WebDrivers and explicit waits.
-
What are soft assertions? Answer: Assertions (
expect.soft()) that do not stop test execution if they fail. Deeper: The test continues, and Playwright marks the test as failed at the very end. -
What is fullyParallel? Answer: A config option that tells Playwright to run tests inside a single file concurrently. Deeper: By default, tests inside
foo.spec.tsrun serially.fullyParallel: trueignores this. -
What are workers? Answer: OS processes spawned by Playwright to run tests in parallel. Deeper: Each worker gets its own browser instance.
-
How do you run tests in CI? Answer: Using GitHub Actions, GitLab CI, or Jenkins using the official Playwright Docker image or
npx playwright install. -
How do you use Docker with Playwright? Answer: Microsoft provides
mcr.microsoft.com/playwright:v1.x.x. Deeper: Ensures visual screenshot tests match exactly, regardless of host OS fonts/rendering. -
What is the role of playwright.config.ts? Answer: The brain of the framework. It configures timeouts, browsers, reporters, and base URLs.
-
How do you handle dynamic elements? Answer: Use semantic locators like
getByRole, filter by text, or use regex matching. -
What is device emulation? Answer: Testing how the page looks on mobile devices. Deeper: Playwright simulates user agents, viewports, and touch events (e.g.,
devices['iPhone 13']). -
How do you organize tests? Answer: By business feature domain folders. Page objects in a
pagesdirectory, helpers inutils. -
What are test tags? Answer: Adding tags like
@smokeor@regressionto test titles. Deeper: You can filter runs usingnpx playwright test --grep "@smoke". -
What is test.step? Answer: A way to group actions in the report.
await test.step('Login', async () => { ... }). Deeper: Makes HTML reports vastly more readable. -
How do you handle cookies? Answer:
context.addCookies()orcontext.cookies(). -
What is the webServer config? Answer: A config setting that tells Playwright to start a local server (e.g.,
npm run dev) before running tests, and shut it down after. -
How do you generate reports? Answer: Configured via the
reporterarray.html,junit,jsonare built-in. -
What is the Playwright Inspector? Answer: A GUI that allows you to step over code line-by-line and test locators live.
-
How do you make tests less flaky? Answer: Remove
waitForTimeout, use web-first assertions, isolate test data, and uselocatorinstead of$!
Section 63: Interview Self-Introduction
30-second answer
"Hi, I'm [Your Name]. I have [X] years of experience in QA and test automation. For the past [Y] years, I've been heavily focused on Playwright and TypeScript, building automation frameworks from scratch. I specialize in CI/CD integration, API/UI hybrid testing, and ensuring stable, flake-free test execution. I'm excited about this role because [Company]'s tech stack aligns perfectly with my Playwright expertise."
1-minute answer
"Hi, I'm [Your Name], an automation engineer with [X] years of experience. My current focus is architecting scalable test frameworks using Playwright and TypeScript. In my current role at [Current Company], I migrated our legacy [Selenium/Cypress] suite to Playwright, reducing test execution time by [Z]%. I heavily utilize Page Object Model, custom fixtures, and API context testing to create isolated, fast tests. I also manage the CI pipeline integrations using [GitHub Actions/Jenkins], configuring sharding and test reporting. I'm passionate about writing clean, maintainable code and mentoring teams on modern testing practices."
2-minute answer
"Hi, I'm [Your Name]. I've spent the last [X] years in software quality engineering, with a deep specialization in TypeScript and Playwright over the past [Y] years.
In my most recent project, we needed a robust E2E solution. I designed a Playwright framework from the ground up. I focused on speed and reliability by bypassing UI setups using Playwright's APIRequestContext and utilizing storageState for session management. I implemented the Page Object Model alongside custom fixtures to make test writing seamless for the rest of the team.
To handle scale, I integrated the suite into [GitHub Actions] using Docker containers and Playwright sharding, which brought our pipeline execution down from an hour to just 10 minutes. I also set up visual regression testing and trace-viewer artifacts so developers could easily debug failures.
Beyond just writing tests, I consider myself an automation architect. I advocate for testability during sprint planning, and I ensure the framework remains clean, DRY, and easy to contribute to. I'm looking for a role where I can bring this expertise to elevate a team's automation maturity, which is why I'm so interested in this position."
Section 64: Project Explanation
How to answer: 'Explain your Playwright automation framework'
"My framework is built on Playwright with TypeScript.
1. Structure & Architecture:
I organized the project by feature domains. We have tests/, pages/ for Page Objects, utils/ for helpers, and fixtures/. This modularity ensures that as the suite grows, it remains maintainable.
2. Design Patterns:
I use the Page Object Model (POM) heavily, but I combine it with Playwright Fixtures. Instead of instantiating page objects inside every test (new LoginPage(page)), I inject them as fixtures. This keeps tests clean and allows for automatic teardowns.
3. Test Data & Authentication:
To keep tests fast, I avoid UI login where possible. I have a globalSetup script that authenticates via our backend API, generates a JWT token, and saves it to a storageState.json file. All subsequent tests use this state to start authenticated. For test data, we use the request API fixture to seed unique data directly into the database before a test runs, ensuring total test isolation.
4. Reporting & CI/CD: The framework runs in CI (GitHub Actions) on every pull request. We utilize Playwright sharding across 4 workers to keep runtimes under 5 minutes. On failure, the pipeline automatically uploads the HTML Report and Trace Viewer zip files as artifacts. This means developers can download the trace, step through the DOM, and see exactly what failed without needing to reproduce it locally.
5. Stability:
We strictly use web-first assertions (toBeVisible) and absolutely zero hardcoded sleeps. This makes our framework highly reliable and practically flake-free."
Potential Follow-up Questions:
- Interviewer: Why did you choose Fixtures over standard BeforeEach hooks?
- You: Fixtures naturally handle setup and teardown together via the
use()function. They also evaluate lazily, meaning if a test doesn't request the fixture, the setup code doesn't run, saving execution time.
- You: Fixtures naturally handle setup and teardown together via the
- Interviewer: How do you handle environment configurations?
- You: I use
dotenvto load.envfiles based on the environment flag. Theplaywright.config.tsreadsprocess.env.BASE_URLto easily switch between Staging and QA.
- You: I use
Section 65: Difficult Interview Follow-Ups
1. Auto-waiting Follow-ups
Interviewer: You mentioned Playwright auto-waits. Does it wait for API responses?
Candidate: No, by default it only auto-waits for DOM actionability—like visibility, stability, and element enabled state.
Interviewer: So how do you handle a button click that triggers a slow API call before showing a success message?
Candidate: The best way is to assert the end state: await expect(page.getByText('Success')).toBeVisible(). The assertion auto-retries. If I specifically need the API payload, I'd use await page.waitForResponse('/api/submit').
2. Authentication Follow-ups
Interviewer: How do you handle scenarios where you need to test as an Admin and a Standard User in the same test suite?
Candidate: I generate two separate storageState files: admin.json and user.json. I can configure specific test directories to use different storage states via the projects array in the config, or explicitly use test.use({ storageState: 'user.json' }) in the test file.
3. CI/CD Follow-ups
Interviewer: Our tests run fine locally but fail randomly in CI. What is your troubleshooting process?
Candidate: First, I'd look at the Trace Viewer artifact from CI. I check the exact DOM state at failure. Usually, it's a timing issue—CI CPUs are slower, so animations or network take longer. I'd ensure we aren't using waitForTimeout, check if viewports match, and maybe increase the timeout for that specific action.
4. Locator Strategy Follow-ups
Interviewer: An element has no unique ID, no text, and changes DOM position. How do you locate it?
Candidate: I'd first ask the devs to add a data-testid. If that's not possible, I look for semantic relations. Can I find a static parent container? I can use page.locator('.parent').filter({ has: page.locator('.child') }). I rely on .filter() and hasText to narrow down elements contextually rather than using fragile XPaths.
5. POM vs Fixtures Follow-ups
Interviewer: If you use Fixtures to inject Page Objects, doesn't that create massive fixture files?
Candidate: It can, which is why I use fixture composition. I create separate fixture files for different domains (e.g., authFixtures, cartFixtures) and merge them using mergeTests(). This keeps the fixture logic highly modular.
6. Flaky Test Follow-ups
Interviewer: How do you definitively prove a test is no longer flaky after fixing it?
Candidate: I run it locally using the --repeat-each=20 flag. If it passes 20 times consecutively, I have high confidence the race condition is fixed.
7. API Testing Follow-ups
Interviewer: Can you intercept and modify an API response for just one specific test?
Candidate: Yes, I can use await page.route('/api/data', route => route.fulfill({ json: customData })) directly inside the test block. It will only mock the response for that specific test context.
8. Network Interception Follow-ups
Interviewer: Our page loads hundreds of heavy images, slowing down tests. How can Playwright help?
Candidate: We can intercept and block image requests globally. In a beforeEach or fixture, I'd write await page.route('**/*.{png,jpg,jpeg}', route => route.abort()). This drastically speeds up UI tests where visuals aren't the focus.
(7 more standard dialogues omitted for brevity, but follow the same pattern of technical depth).
Section 66: Final Revision Roadmap
Level 1 — Must Know (Core Fundamentals)
- Locators:
getByRole,getByText, CSS selectors. Know why accessibility locators are preferred. - Actions: Click, fill, check, selectOption.
- Assertions:
toBeVisible,toHaveText,toHaveValue. Difference between web-first and generic assertions. - Auto-waiting: Understand the actionability checks (Visible, Stable, Enabled).
Level 2 — Should Know (Framework Building)
- Page Object Model (POM): How to structure classes, encapsulate locators, and separate actions from assertions.
- Configuration:
playwright.config.tssettings (timeouts, retries, baseURL). - Test Hooks:
beforeEach,afterEach,beforeAll. - Debugging: How to use Trace Viewer, HTML Reporter, and
PWDEBUG.
Level 3 — Advanced (Playwright Specifics)
- Fixtures: Creating custom fixtures,
use, understandingworkervstestscope. - storageState: Managing authentication state without UI logins.
- Network Interception:
page.route(), mocking API responses, aborting requests. - API Testing: Using
requestcontext (APIRequestContext) for setup/teardown and validation.
Level 4 — Production (CI/CD & Architecture)
- Parallelism & Sharding: How Playwright workers operate, configuring fullyParallel, splitting runs in GitHub Actions.
- Docker: Using the official Playwright Docker image for consistent CI environments.
- Test Isolation strategies: Managing database state, ensuring tests run independently.
Level 5 — Interview Practice (Communication)
- Practice your 1-minute introduction.
- Be able to draw/explain your framework architecture.
- Prepare stories of how you fixed a difficult flaky test.
- Prepare your reasoning for "Why Playwright over X?"
End of Study Guide