-->

Featured

DSA Interview Question

Question: Various S orting algorithms Answer: There are various sorting algorithms, each with its own advantages and disadvantages in terms ...

PlayWright

Question: What is Playwright?

Answer:

Playwright is an open-source end-to-end automation testing framework developed by Microsoft. It supports automation of Chromium, Firefox, and WebKit browsers using a single API. Playwright provides fast, reliable, and cross-browser testing with built-in support for auto-waiting, multiple browser contexts, network interception, screenshots, videos, and parallel execution.


Question: What are the key features of Playwright?

Answer:

  • Supports Chromium, Firefox, and WebKit.
  • Cross-platform support (Windows, Linux, macOS).
  • Supports JavaScript, TypeScript, Java, Python, and .NET.
  • Automatic waiting for elements.
  • Supports multiple browser contexts.
  • Parallel test execution.
  • Network interception and API mocking.
  • Captures screenshots, videos, and traces.
  • Supports mobile device emulation.

Question: Which browsers are supported by Playwright?

Answer:

Playwright supports the following browsers:

  • Google Chrome / Chromium
  • Microsoft Edge
  • Mozilla Firefox
  • Safari (WebKit)

Question: What is Browser Context in Playwright?

Answer:

A Browser Context is an isolated browser session. Multiple contexts can run inside a single browser instance without sharing cookies, cache, or local storage. It is useful for testing multiple users simultaneously.

Example: Create a browser context.

const browser = await chromium.launch();

const context = await browser.newContext();

const page = await context.newPage();

Note: Browser Contexts are lightweight and faster than launching multiple browser instances.


Question: What is the difference between Browser and Browser Context?

Answer:

Browser:

  • Represents the browser application.
  • Consumes more resources.
  • Can contain multiple browser contexts.

Browser Context:

  • Represents an isolated browser session.
  • Shares the browser process.
  • Has separate cookies, cache, and storage.

Question: What is auto-waiting in Playwright?

Answer:

Playwright automatically waits for elements before performing actions. It waits until the element becomes:

  • Visible
  • Stable
  • Enabled
  • Ready to receive events

Example:

await page.locator("#login").click();

Note: Unlike Selenium, Playwright usually does not require explicit waits before clicking or typing.


Question: How do you launch a browser in Playwright?

Answer:

Example: Launch Chromium browser.

import { chromium } from '@playwright/test';

const browser = await chromium.launch({
    headless: false
});

const page = await browser.newPage();

await page.goto("https://example.com");

Question: How do you locate elements in Playwright?

Answer:

Playwright provides multiple locator strategies.

  • getByRole()
  • getByText()
  • getByLabel()
  • getByPlaceholder()
  • getByAltText()
  • getByTitle()
  • getByTestId()
  • locator()
  • CSS Selector
  • XPath

Example:

await page.getByRole('button', {
    name: 'Login'
}).click();

await page.locator("#username").fill("admin");

Question: What is Locator in Playwright?

Answer:

A Locator represents a way to find elements on the page. It automatically retries until the element satisfies the required conditions, making tests more reliable.

Example:

const loginButton = page.locator("#login");

await loginButton.click();

Question: What is the difference between Locator and ElementHandle?

Answer:

Locator:

  • Automatically waits for elements.
  • Retries until action succeeds.
  • Recommended by Playwright.

ElementHandle:

  • Represents a fixed DOM element.
  • Does not auto-retry.
  • Can become stale if the DOM changes.

Note: Prefer using Locators instead of ElementHandle.


Question: How do you take screenshots in Playwright?

Answer:

Example: Capture the full page screenshot.

await page.screenshot({
    path: "homepage.png",
    fullPage: true
});

Question: How do you upload a file in Playwright?

Answer:

Example:

await page.locator("input[type='file']")
    .setInputFiles("sample.pdf");

Question: How do you handle alerts in Playwright?

Answer:

Playwright listens for dialog events.

Example:

page.on("dialog", async dialog => {
    console.log(dialog.message());
    await dialog.accept();
});

await page.locator("#alert").click();

Question: How do you perform assertions in Playwright?

Answer:

Playwright provides built-in assertions through the expect() API.

Example:

await expect(page).toHaveTitle("Home");

await expect(page.locator("#login"))
    .toBeVisible();

Question: What is Trace Viewer in Playwright?

Answer:

Trace Viewer is a debugging tool that records every action performed during test execution, including screenshots, DOM snapshots, console logs, network requests, and timing information.

Example: Enable tracing.

await context.tracing.start({
    screenshots: true,
    snapshots: true
});

...

await context.tracing.stop({
    path: "trace.zip"
});

Note: Trace Viewer is one of the most powerful debugging features available in Playwright.

Question: How do you navigate to a URL in Playwright?

Answer:

Playwright uses the goto() method to navigate to a web page.

Example: Navigate to a website.

await page.goto("https://www.google.com");

Note: The goto() method waits until the page reaches the default load state before continuing.


Question: How do you perform mouse actions in Playwright?

Answer:

Playwright provides various mouse actions such as click, double-click, right-click, hover, and drag-and-drop.

Example: Mouse actions.

// Click
await page.locator("#btn").click();

// Double Click
await page.locator("#btn").dblclick();

// Right Click
await page.locator("#btn").click({
    button: "right"
});

// Hover
await page.locator("#menu").hover();

Question: How do you perform keyboard actions in Playwright?

Answer:

Keyboard actions are performed using the keyboard object.

Example:

await page.keyboard.type("Playwright");

await page.keyboard.press("Enter");

await page.keyboard.press("Control+A");

await page.keyboard.press("Backspace");

Question: How do you handle dropdowns in Playwright?

Answer:

The selectOption() method is used to select values from a dropdown.

Example:

await page.locator("#country")
    .selectOption("India");

await page.locator("#country")
    .selectOption({ label: "India" });

await page.locator("#country")
    .selectOption({ index: 2 });

Question: How do you check or uncheck a checkbox in Playwright?

Answer:

Playwright provides dedicated methods to work with checkboxes.

Example:

await page.locator("#agree").check();

await page.locator("#agree").uncheck();

await expect(page.locator("#agree"))
    .toBeChecked();

Question: How do you work with radio buttons in Playwright?

Answer:

Radio buttons can be selected using the check() method.

Example:

await page.locator("#male").check();

await expect(page.locator("#male"))
    .toBeChecked();

Question: How do you handle multiple tabs in Playwright?

Answer:

Playwright uses the waitForEvent('page') method to capture newly opened tabs.

Example:

const pagePromise =
    context.waitForEvent("page");

await page.locator("#newTab").click();

const newPage = await pagePromise;

await newPage.waitForLoadState();

Question: How do you handle multiple browser windows in Playwright?

Answer:

Every newly opened browser window is represented as a new Page object.

Example:

const popupPromise =
    page.waitForEvent("popup");

await page.locator("#window")
    .click();

const popup = await popupPromise;

await popup.waitForLoadState();

Question: How do you handle file downloads in Playwright?

Answer:

Playwright provides download events for handling downloaded files.

Example:

const downloadPromise =
    page.waitForEvent("download");

await page.locator("#download")
    .click();

const download =
    await downloadPromise;

await download.saveAs("report.pdf");

Question: How do you perform drag and drop in Playwright?

Answer:

Playwright provides the dragTo() method.

Example:

await page.locator("#source")
    .dragTo(
        page.locator("#target")
    );

Question: How do you scroll a page in Playwright?

Answer:

Pages can be scrolled using JavaScript or locator methods.

Example:

await page.evaluate(() => {
    window.scrollTo(0,
    document.body.scrollHeight);
});

await page.locator("#footer")
    .scrollIntoViewIfNeeded();

Question: How do you execute JavaScript in Playwright?

Answer:

The evaluate() method executes JavaScript inside the browser.

Example:

String title =
await page.evaluate(() =>
document.title);

await page.evaluate(() => {
    localStorage.clear();
});

Question: How do you wait for an element in Playwright?

Answer:

Although Playwright automatically waits for most actions, explicit waiting is available when needed.

Example:

await page.locator("#login")
    .waitFor();

await page.waitForSelector(
    "#username"
);

Note: Explicit waits should be used only when auto-waiting is insufficient.


Question: How do you handle authentication in Playwright?

Answer:

Authentication state can be saved and reused to avoid logging in before every test.

Example:

await context.storageState({
    path: "auth.json"
});

Example: Reuse authentication.

const context =
await browser.newContext({
    storageState: "auth.json"
});

Question: What is Playwright Test Runner?

Answer:

Playwright Test Runner is the built-in testing framework that supports:

  • Parallel execution.
  • Retries.
  • Fixtures.
  • Projects.
  • HTML reports.
  • Screenshots.
  • Video recording.
  • Trace Viewer.

Question: What are Fixtures in Playwright?

Answer:

Fixtures are reusable setup and teardown components shared across tests.

Example:

test("Login Test",
async ({ page }) => {

    await page.goto(
        "https://example.com"
    );

});

Note: The page object is provided automatically by the Playwright fixture.


Question: How do you run tests in parallel in Playwright?

Answer:

Parallel execution is configured using the workers property.

Example:

export default defineConfig({

    workers: 4

});

Question: How do you retry failed tests in Playwright?

Answer:

The retries option automatically reruns failed tests.

Example:

export default defineConfig({

    retries: 2

});

Question: How do you generate an HTML report in Playwright?

Answer:

Playwright can generate rich HTML reports after test execution.

Example:

export default defineConfig({

    reporter: "html"

});

Command:

npx playwright show-report

Question: Why is Playwright preferred over Selenium?

Answer:

  • Built-in auto waiting.
  • Faster execution.
  • Supports Chromium, Firefox, and WebKit.
  • No separate browser drivers are required.
  • Supports network interception.
  • Supports parallel execution by default.
  • Built-in screenshots, videos, and tracing.
  • Provides more reliable locators.
  • Excellent debugging capabilities.

Note: Playwright is increasingly adopted for modern web application testing because of its speed, stability, and rich feature set.

Question: How do you handle dynamic web elements in Playwright?

Answer:

Dynamic web elements frequently change their attributes such as id, class, or name. In Playwright, it is recommended to use stable locators like getByRole(), getByLabel(), getByTestId(), or CSS selectors instead of dynamic IDs.

Example: Using a stable locator.

await page.getByRole("button", {
    name: "Login"
}).click();

Note: Avoid using dynamically generated IDs whenever possible.


Question: How do you handle hidden elements in Playwright?

Answer:

Hidden elements cannot be interacted with until they become visible. Playwright automatically waits for elements to become visible before performing actions.

Example:

await page.locator("#submit")
    .waitFor();

await page.locator("#submit")
    .click();

Question: How do you handle loading spinners in Playwright?

Answer:

Wait until the loading spinner disappears before interacting with page elements.

Example:

await page.locator(".loader")
    .waitFor({
        state: "hidden"
    });

await page.locator("#save")
    .click();

Question: How do you verify toast messages in Playwright?

Answer:

Locate the toast notification and verify its text using Playwright assertions.

Example:

await expect(
    page.locator(".toast")
).toHaveText(
    "Record Saved Successfully"
);

Question: How do you handle network API calls in Playwright?

Answer:

Playwright provides waitForResponse() to wait until a specific API call completes.

Example:

await Promise.all([

page.waitForResponse(
response =>
response.url().includes("/login")
&& response.status() == 200
),

page.locator("#login")
.click()

]);

Note: This is more reliable than using fixed waits.


Question: How do you mock API responses in Playwright?

Answer:

Playwright allows intercepting network requests using the route() method.

Example:

await page.route(
"**/users",
route => {

route.fulfill({

status:200,

body: JSON.stringify([
{
name:"John"
}
])

});

});

Question: How do you block unnecessary network requests in Playwright?

Answer:

Images, fonts, and advertisements can be blocked to improve execution speed.

Example:

await page.route(

"**/*.{png,jpg,jpeg,gif}",

route => route.abort()

);

Question: How do you handle stale element problems in Playwright?

Answer:

Unlike Selenium, Playwright locators automatically re-query the DOM before every action, reducing stale element issues.

Example:

await page.locator("#login")
.click();

Note: Always use Locator instead of storing ElementHandle objects.


Question: How do you capture browser console logs in Playwright?

Answer:

Console messages can be captured using the console event.

Example:

page.on("console",

msg => {

console.log(msg.text());

});

Question: How do you capture failed screenshots automatically?

Answer:

Configure Playwright Test to capture screenshots only for failed tests.

Example:

export default defineConfig({

use:{

screenshot:
"only-on-failure"

}

});

Question: How do you record videos of failed tests?

Answer:

Playwright can automatically record videos during test execution.

Example:

export default defineConfig({

use:{

video:
"retain-on-failure"

}

});

Question: How do you perform data-driven testing in Playwright?

Answer:

Use JavaScript arrays, JSON files, or CSV files to execute the same test with multiple datasets.

Example:

const users = [

"Admin",

"Manager",

"Guest"

];

for(const user of users){

test(user,

async ({page})=>{

// Test logic

});

}

Question: How do you run the same test in multiple browsers?

Answer:

Playwright Projects allow the same test to run on Chromium, Firefox, and WebKit.

Example:

projects:[

{
name:"Chromium"
},

{
name:"Firefox"
},

{
name:"WebKit"
}

]

Question: How do you handle environment-specific URLs in Playwright?

Answer:

Store URLs inside environment variables or configuration files instead of hardcoding them.

Example:

await page.goto(

process.env.BASE_URL!

);

Question: How do you organize a Playwright automation framework?

Answer:

  • Page Object Model (POM).
  • Utility classes.
  • Common fixtures.
  • Test data folder.
  • Environment configuration.
  • API helper classes.
  • Custom reporting.
  • Reusable assertions.

Note: A well-structured framework improves code reusability and maintainability.


Question: A button is visible but Playwright cannot click it. How would you troubleshoot?

Answer:

  • Verify the locator.
  • Check if another element overlaps the button.
  • Wait for animations to complete.
  • Verify the element is enabled.
  • Inspect browser console errors.
  • Use Trace Viewer for debugging.
  • Check if the button is inside an iframe.

Example:

await expect(
page.locator("#save")
).toBeVisible();

await expect(
page.locator("#save")
).toBeEnabled();

await page.locator("#save")
.click();

Question: What is the difference between page.waitForSelector() and Locator in Playwright?

Answer:

Locator is the recommended approach in Playwright because it automatically waits for elements before every action, whereas page.waitForSelector() waits only once and returns an ElementHandle.

Locator:

  • Automatically retries until the action succeeds.
  • Supports auto waiting.
  • Recommended by Playwright.

waitForSelector():

  • Returns an ElementHandle.
  • Can become stale if the DOM changes.
  • Mainly used for legacy code.

Example:

await page.locator("#login").click();

Note: Prefer Locator APIs over waitForSelector() in new projects.


Question: How do you handle Shadow DOM elements in Playwright?

Answer:

Playwright automatically pierces open Shadow DOM, so no special API is required.

Example:

await page
.locator("custom-component")
.locator("#username")
.fill("admin");

Note: Closed Shadow DOM cannot be accessed by any automation framework.


Question: How do you intercept and modify API requests in Playwright?

Answer:

The route() method allows modification of outgoing requests before they reach the server.

Example:

await page.route("**/login",

async route=>{

const request=route.request();

const data=request.postDataJSON();

data.username="Admin";

await route.continue({

postData:JSON.stringify(data)

});

});

Question: How do you verify REST API responses while testing UI in Playwright?

Answer:

Use waitForResponse() and validate the response body before continuing with UI validation.

Example:

const response=
await page.waitForResponse(

res=>res.url().includes("/users")

);

expect(response.status())
.toBe(200);

const body=
await response.json();

Question: How do you test WebSocket communication in Playwright?

Answer:

Playwright allows listening to WebSocket events for validating real-time communication.

Example:

page.on("websocket",

ws=>{

console.log(ws.url());

});

Question: How do you test file downloads without saving them to disk?

Answer:

The download object can be inspected without permanently storing the file.

Example:

const download=

await page.waitForEvent(
"download"
);

console.log(

download.suggestedFilename()

);

Question: How do you reduce flaky tests in Playwright?

Answer:

  • Use Locators instead of ElementHandle.
  • Avoid fixed waits.
  • Wait for API responses instead of UI delays.
  • Use stable selectors.
  • Use Browser Context isolation.
  • Use retries only as a last resort.
  • Review traces for failures.

Note: Most flaky tests are caused by synchronization issues rather than Playwright itself.


Question: How do you test multiple users simultaneously in Playwright?

Answer:

Create multiple Browser Contexts within the same browser instance.

Example:

const admin=

await browser.newContext();

const customer=

await browser.newContext();

const adminPage=

await admin.newPage();

const customerPage=

await customer.newPage();

Question: How do you handle authentication using API instead of UI login?

Answer:

Login using Playwright's APIRequestContext, store the authentication state, and reuse it across tests.

Example:

await request.post(

"/login",

{

data:{

username:"admin",

password:"admin"

}

});

Note: API login significantly reduces execution time.


Question: What is APIRequestContext in Playwright?

Answer:

APIRequestContext allows sending HTTP requests directly without opening a browser.

Example:

const response=

await request.get(

"/users"

);

expect(response.ok())

.toBeTruthy();

Question: How do you test responsive websites in Playwright?

Answer:

Create browser contexts with different viewport sizes or use built-in device emulation.

Example:

const context=

await browser.newContext({

viewport:{

width:390,

height:844

}

});

Question: How do you debug failed Playwright tests?

Answer:

  • Trace Viewer.
  • Inspector Mode.
  • Screenshots.
  • Videos.
  • Console Logs.
  • Network Logs.
  • PWDEBUG environment variable.

Example:

PWDEBUG=1

npx playwright test

Question: Explain the execution flow of Playwright.

Answer:

  • Playwright Test Runner starts execution.
  • Browser launches.
  • Browser Context is created.
  • Page object is initialized.
  • Locators identify elements.
  • Auto waiting ensures readiness.
  • Actions are performed.
  • Assertions validate results.
  • Reports, screenshots, videos and traces are generated.

Question: What are the best practices for designing a Playwright framework?

Answer:

  • Use Page Object Model.
  • Separate test data.
  • Create reusable utility classes.
  • Implement custom fixtures.
  • Use environment configuration.
  • Generate HTML reports.
  • Enable tracing for failures.
  • Use TypeScript instead of JavaScript.
  • Avoid duplicate locators.
  • Follow SOLID principles.

Question: Your Playwright tests pass locally but fail in Jenkins. How would you investigate?

Answer:

  • Compare browser versions.
  • Verify Playwright version.
  • Check environment variables.
  • Review Jenkins logs.
  • Inspect screenshots and traces.
  • Verify network availability.
  • Check headless-specific issues.
  • Verify permissions and file paths.
  • Look for timing differences.
  • Run the failed test with Trace Viewer.

Note: Environment differences are the most common cause of CI/CD failures.

Question: What are the different types of Assertions available in Playwright?

Answer:

Playwright provides two types of assertions:

  • Auto-Retry Assertions – Automatically wait until the expected condition becomes true.
  • Non-Retry Assertions – Immediately verify the condition without waiting.

Common Auto-Retry Assertions:

  • toBeVisible()
  • toBeHidden()
  • toBeEnabled()
  • toBeDisabled()
  • toBeEditable()
  • toBeChecked()
  • toBeEmpty()
  • toContainText()
  • toHaveText()
  • toHaveValue()
  • toHaveCount()
  • toHaveAttribute()
  • toHaveClass()
  • toHaveCSS()
  • toHaveId()
  • toHaveJSProperty()
  • toHaveRole()
  • toHaveTitle()
  • toHaveURL()

Example:

await expect(
page.locator("#login")
).toBeVisible();

Question: Explain commonly used Playwright Assertions with descriptions.

Answer:

Assertion Description
toBeVisible() Verifies that an element is visible.
toBeHidden() Verifies that an element is hidden.
toBeEnabled() Checks whether an element is enabled.
toBeDisabled() Checks whether an element is disabled.
toBeEditable() Checks whether an input field is editable.
toBeChecked() Verifies checkbox or radio button selection.
toHaveText() Verifies exact text.
toContainText() Verifies partial text.
toHaveValue() Verifies input field value.
toHaveCount() Verifies number of matching elements.
toHaveAttribute() Verifies an attribute value.
toHaveClass() Verifies CSS class.
toHaveCSS() Verifies CSS property value.
toHaveTitle() Verifies page title.
toHaveURL() Verifies current URL.

Question: What are the different Actions supported in Playwright?

Answer:

Playwright provides various built-in actions for interacting with web elements.

Action Description
click() Clicks an element.
dblclick() Double-clicks an element.
check() Selects a checkbox.
uncheck() Unselects a checkbox.
fill() Enters text into an input field.
clear() Clears an input field.
hover() Moves mouse over an element.
dragTo() Performs drag and drop.
focus() Sets focus on an element.
press() Presses a keyboard key.
pressSequentially() Types characters one by one.
setInputFiles() Uploads files.
selectOption() Selects dropdown values.
scrollIntoViewIfNeeded() Scrolls to the element.
screenshot() Takes element screenshot.

Question: What are the different Locator methods available in Playwright?

Answer:

Playwright provides multiple modern locator strategies.

Locator Description
locator() Generic locator using CSS or XPath.
getByRole() Finds elements using ARIA role.
getByText() Finds element by visible text.
getByLabel() Finds input using associated label.
getByPlaceholder() Finds element using placeholder.
getByAltText() Finds image using alt text.
getByTitle() Finds element using title attribute.
getByTestId() Finds element using test-id.
frameLocator() Locates elements inside iframe.

Question: What are the commonly used Page methods in Playwright?

Answer:

Method Description
goto() Navigate to URL.
reload() Reload current page.
goBack() Navigate back.
goForward() Navigate forward.
title() Returns page title.
url() Returns current URL.
content() Returns page HTML.
evaluate() Executes JavaScript.
waitForLoadState() Waits until page loads.
waitForResponse() Waits for API response.
waitForRequest() Waits for request.
waitForEvent() Waits for browser events.
route() Intercepts network requests.
screenshot() Takes page screenshot.
pdf() Generates PDF (Chromium).

Question: What are the commonly used Browser Context methods?

Answer:

Method Description
newPage() Creates a new page.
close() Closes browser context.
cookies() Returns cookies.
clearCookies() Deletes cookies.
grantPermissions() Grants browser permissions.
storageState() Saves authentication state.
addInitScript() Runs JavaScript before page loads.
setDefaultTimeout() Sets default timeout.

No comments:

Post a Comment

popular posts