Crack Playwright Java Interviews sample book front cover

Download the Free Sample Book

Try the sample before buying the full ebook.

The sample book contains 100+ selected Playwright Java interview questions and answers. Use it to check the content style, answer depth, Java examples, and practical explanation approach.

For the complete ebook with 1800+ questions, visit the Buy Ebook page.

Selected free questions with full answers

These examples show the style of the full ebook.

Question 1.1

What is Playwright, and why is it used in test automation?

Interview-Style Answer

Playwright is a modern end-to-end testing and browser automation tool used to test modern web applications reliably.

It is used because modern applications are dynamic and need stable automation. Playwright makes tests more reliable with features like auto-waiting, web-first assertions, browser context isolation, tracing which help reduce flaky test failures.

Playwright provides one API to test across different browsers, platforms, and languages. It supports Chromium, Firefox, WebKit, Windows, Linux, macOS, and languages like Java, JavaScript, TypeScript, Python, and .NET.

It also supports important real-project testing needs such as mobile web emulation, multiple tabs, multiple users, iframes, Shadow DOM, API testing, mock APIs, and network interception.

For faster test creation and debugging, Playwright provides useful tools like Codegen, Playwright Inspector, and Trace Viewer. Codegen helps generate test scripts by recording user actions, Inspector helps debug step by step, and Trace Viewer helps analyze failures with screenshots, DOM snapshots, actions, and network details.

Detailed Explanation

Playwright is useful because modern web applications are not simple static pages. They are usually dynamic, asynchronous, and heavily dependent on JavaScript, APIs, animations, validations, and real-time UI updates. Because of this, automation tools must wait correctly, interact like real users, and provide strong debugging support. Playwright solves these needs by providing reliable browser automation with built-in waiting, strong assertions, and powerful test execution features.

One major reason Playwright is reliable is auto-waiting. Before performing actions like click(), fill(), or selectOption(), Playwright automatically waits until the element is ready for action. This reduces the need for hard waits like Thread.sleep(), which often make tests slow and flaky. Its web-first assertions also retry validations until the expected condition is met, making checks more stable for dynamic pages.

Playwright also gives better test isolation using browser contexts. Each test can run in a fresh browser context, similar to a new browser profile, with separate cookies, local storage, sessions, and permissions. This prevents one test from affecting another. At the same time, authentication state can be saved and reused, so teams can avoid repeated login steps while still keeping tests isolated.

It is also suitable for real project scenarios because it supports cross-browser testing, mobile web emulation, multiple tabs, multiple users, iframes, Shadow DOM, API testing, mock APIs, and network interception. This means the same framework can validate both UI behavior and backend/API behavior, and it can also mock responses to test success, failure, empty data, or server-error scenarios.

For faster development and debugging, Playwright provides tools like Codegen, Playwright Inspector, and Trace Viewer. Codegen helps create test scripts by recording user actions. Inspector helps debug tests step by step. Trace Viewer helps analyze failures using screenshots, DOM snapshots, actions, source code, and network details.

Common mistake: treating Playwright only as a browser automation tool. In real projects, it is a complete end-to-end testing framework for reliable, isolated, cross-browser, API-enabled, mock-supported, and debuggable automation.



Question 1.2

Why is Playwright considered suitable for testing modern web applications like React, Angular, and Vue apps?

Interview-Style Answer

Playwright is suitable for modern web applications because it is designed to handle dynamic UI behavior, asynchronous DOM updates, auto-waiting, reliable locators, and stable assertions. This makes it effective for testing applications built with frameworks like React, Angular, and Vue, where elements can appear, disappear, or change state without a full page reload.

Detailed Explanation

Modern web applications are usually dynamic. In frameworks like React, Angular, and Vue, the page does not always reload fully after every action. Instead, the application updates only parts of the DOM.

For example:

  • A button may become enabled after an API response.
  • A list may update after filtering.
  • A modal may appear after a user action.
  • A component may re-render after state change.
  • A loading spinner may disappear after data is loaded.

Traditional automation tools may struggle with these asynchronous changes because they often try to interact with elements before the UI is ready.

Playwright helps solve this problem through auto-waiting. Before performing actions, Playwright waits for the element to be ready for interaction. It checks conditions such as:

  • Element is visible.
  • Element is stable.
  • Element is enabled.
  • Element is ready to receive user action.

This reduces the need for hard waits like Thread.sleep() and makes tests more reliable.

Playwright also provides web-first assertions. These assertions automatically retry until the expected condition becomes true or the timeout is reached. This is very useful in SPAs because UI updates may happen after a short delay.

Another major advantage is its locator strategy. Playwright encourages user-facing locators such as:

  • getByRole()
  • getByText()
  • getByLabel()

These locators are based on how users see and interact with the application, rather than depending heavily on fragile DOM structures. This is especially useful in React, Angular, and Vue applications where DOM structure may change because of component re-rendering.

Example Scenario

Suppose a React application loads a “Submit” button only after form validation is complete.

With Playwright, we can write:

page.getByRole(AriaRole.BUTTON,
  new Page.GetByRoleOptions().setName("Submit")).click();

Playwright will wait until the button is ready for interaction before clicking it.

Common mistake:

A common mistake is treating modern web apps like static HTML pages.

In SPAs, the UI changes dynamically. So, using fixed waits, fragile XPath, or immediate assertions can create flaky tests. Playwright is preferred because it works naturally with dynamic UI behavior through auto-waiting, retrying assertions, and reliable locators.



Question 1.35

How do you validate toast notifications in Playwright?

Interview-Style Answer

I would validate toast notifications by locating the toast message using a stable role, text content, or test ID, then asserting the exact notification text and visible state. If the toast is expected to auto-close, I would also assert that it disappears after the expected duration.

In Playwright Java, this ensures the test verifies both the correct user-visible feedback and its lifecycle. This approach avoids flakiness when multiple toasts may appear or overlap.

Detailed Explanation

Toast notifications are transient and may appear dynamically after user actions. Proper validation should ensure that the correct toast is matched and no unrelated notification is accidentally captured.

Key checks:

1. Correct toast text appears for the action.
2. Correct toast type or status (success, error, warning) if user-visible.
3. Toast is triggered by the intended user action.
4. Toast disappears automatically if expected.
5. No old or unrelated toast is matched.
6. Multiple simultaneous toasts are handled correctly.

Example:

// Trigger the action that shows the toast
page.getByRole(
    AriaRole.BUTTON,
    new Page.GetByRoleOptions().setName("Submit")
).click();

// Locate the toast notification
Locator toast = page.getByRole(AriaRole.STATUS)
    .filter(new Locator.FilterOptions().setHasText("Submitted successfully"));

// Assert the toast is visible
PlaywrightAssertions.assertThat(toast).isVisible();

// Optional: Assert toast disappears if auto-close is expected
PlaywrightAssertions.assertThat(toast).isHidden();

For multiple toasts:

List<Locator> toasts = page.locator(".toast").all();
for (Locator t : toasts) {
    System.out.println(t.innerText());
}

Common mistake: Selecting the first toast on the page without scoping to the current user action, which can cause validation of an old or unrelated notification and make the test flaky.



Question 1.46

How do you wait for an element to disappear after submitting a form?

Interview-Style Answer

I would use assertThat(locator).isHidden() if the element should remain in the DOM but become invisible, or assertThat(locator).isDetached() if the element should be removed from the DOM entirely. After the element disappears, I would also validate the final expected outcome, such as a success message, updated record, or refreshed table.

This ensures the test proves both that the transient element is gone and that the user-visible result is correct.

Detailed Explanation

UI elements can disappear in two ways:

  • Hidden: The element stays in the DOM but is visually hidden (e.g., a loading spinner fading out).
  • Detached: The element is removed from the DOM (e.g., a modal or temporary notification).

The assertion you choose depends on the application’s behavior.

Example for a hidden spinner:

Locator spinner = page.getByTestId("saving-spinner");

page.getByRole(
    AriaRole.BUTTON,
    new Page.GetByRoleOptions().setName("Submit")
).click();

// Wait for the spinner to become hidden
PlaywrightAssertions.assertThat(spinner).isHidden();

// Validate final result
PlaywrightAssertions.assertThat(
    page.getByText("Saved successfully")
).isVisible();

Example for a detached modal:

Locator modal = page.getByRole(
    AriaRole.DIALOG,
    new Page.GetByRoleOptions().setName("Edit Customer")
);

modal.getByRole(AriaRole.BUTTON, new Locator.GetByRoleOptions().setName("Save")).click();

// Wait for the modal to be removed from the DOM
PlaywrightAssertions.assertThat(modal).isDetached();

// Validate saved changes
PlaywrightAssertions.assertThat(page.getByText("Customer updated successfully")).isVisible();

Key points:

- Choose `isHidden()` vs `isDetached()` based on how the element disappears.
- Always validate the final visible outcome, not only the transient element.
- Use web-first assertions instead of fixed sleeps for stability.

Common mistake: Waiting only for the spinner or modal to disappear without checking that the actual operation completed successfully, which can result in false-positive tests.



Question 1.10

How do you review a Playwright test for maintainability?

Interview-Style Answer

I review whether the test has a clear business purpose, readable structure, stable locators, meaningful assertions, isolated data, and reliable synchronization. A maintainable Playwright test should be easy to understand, safe to run in CI, and simple to debug when it fails.

I also check whether the test follows team standards: proper Page Object or component usage, no hard waits, no shared mutable data, no hidden assertions, and no unnecessary implementation details in the test body.

Detailed Explanation

A maintainable Playwright Java test should tell a clear business story. A reviewer should be able to understand what the test proves without reading every internal locator or knowing the page’s DOM structure.

Example:

@Test
void shouldApprovePendingOrder() {
    // Arrange
    String orderId = testDataApi.createPendingOrder();

    // Act
    ordersPage.open(orderId);
    ordersPage.approveOrder();

    // Assert
    ordersPage.shouldShowStatus("Approved");
}

I would review the test against these points:

- Does the test validate one clear business outcome?
- Is the Arrange-Act-Assert structure visible?
- Are locators based on user intent, such as role, label, text, or stable test IDs?
- Are assertions meaningful and tied to business state?
- Does the test avoid Thread.sleep() and hard waits?
- Does each test own its data?
- Is BrowserContext/Page isolation handled correctly?
- Are repeated actions moved to readable Page Object or component methods?
- Are important assertions visible or clearly named?
- Is cleanup targeted and safe for parallel execution?

I would also check locator quality. This is harder to maintain:

page.locator(".btn-primary:nth-child(2)").click();

This is usually clearer:

page.getByRole(
    AriaRole.BUTTON,
    new Page.GetByRoleOptions().setName("Approve")
).click();

For synchronization, I would reject hard waits and prefer web-first assertions or meaningful event waits:

PlaywrightAssertions.assertThat(
    page.getByTestId("order-status")
).hasText("Approved");

From a framework point of view, maintainability also includes ownership and review rules. Teams should agree on locator strategy, Page Object boundaries, data setup patterns, artifact capture, naming conventions, and CI execution standards. This keeps the suite scalable as more tests and contributors are added.

Common mistake: Reviewing only whether the test passes, without checking whether it has a clear business purpose, stable locator strategy, isolated data, meaningful assertions, reliable synchronization, and long-term maintainability in CI.



Question 1.13

How would you avoid duplicate or low-value tests in a Playwright Java suite?

Interview-Style Answer

I would avoid duplicate or low-value tests by reviewing whether each test validates a unique business risk, has meaningful assertions, and belongs at the right test level. Not every UI scenario needs to be an end-to-end Playwright test.

In a healthy Playwright Java suite, test value should be measured by risk coverage, defect detection, maintainability, and CI execution cost, not by the total number of tests.

Detailed Explanation

Duplicate tests increase execution time, maintenance effort, flakiness, and CI cost without improving confidence. Two tests may not look identical in code, but they can still validate the same behavior through slightly different data or navigation paths.

A useful review checklist is:

1. Does this test validate a unique business behavior?
2. Is the same risk already covered by another test?
3. Does the test have a clear pass/fail business assertion?
4. Is this scenario better covered by an API, unit, or component test?
5. Does the test repeat a long setup flow only to check a small variation?
6. Will this test catch a real regression?
7. Is the ownership of this test clear?
8. Is the test stable enough for regular CI execution?

A low-value test usually performs UI actions without validating a meaningful outcome:

Click a button and assert that another button is visible, without checking whether the expected business state changed.

A better Playwright test should connect the action to a user-visible result:

page.getByRole(
    AriaRole.BUTTON,
    new Page.GetByRoleOptions().setName("Submit Order")
).click();

PlaywrightAssertions.assertThat(
    page.getByText("Order submitted successfully")
).isVisible();

PlaywrightAssertions.assertThat(
    page.getByTestId("order-status")
).hasText("Submitted");

To control duplication, teams should define review rules for new tests. For example, every new Playwright test should explain the risk it covers, the expected business outcome, and why it belongs in the UI suite instead of a lower-level test. Existing tests should be periodically reviewed for overlap, weak assertions, unstable flows, and scenarios that can be moved to API or component coverage.

Good suite governance includes grouping tests by feature area, assigning ownership, tagging smoke/regression tests, tracking flaky tests, and removing tests that no longer provide unique value.

Common mistake: judging automation maturity by the number of Playwright tests, while ignoring duplicate coverage, weak assertions, long CI execution time, and tests that do not protect any meaningful business behavior.



Question 1.6

How would you identify the top 20% of tests that provide 80% of regression value?

Interview-Style Answer

I would identify the top 20% regression tests by mapping each test to business-critical workflows, production usage, customer impact, defect history, release-blocking value, compliance risk, and integration importance.

The most valuable tests are not always the fastest or longest tests. They are the tests that give the highest release confidence. For example, login, checkout, payment, approval, permission checks, data submission, critical reporting, and third-party integrations often provide high regression value because failure in these areas directly affects users or business operations.

I would score tests using objective signals such as escaped defects, production usage, module criticality, failure impact, and how often the test detects real regressions. These tests can become the core smoke or critical regression suite.

Detailed Explanation

The top 20% of regression tests should be selected based on release confidence, not simply based on test count or execution speed. A short test may be valuable if it protects a critical permission rule. A long test may be low-value if it only repeats coverage already tested elsewhere.

I would start by building a test inventory with details such as module, business workflow, owner, runtime, flakiness, defect history, production usage, customer impact, and execution frequency. Then I would rank tests by risk and value.

Useful evaluation factors include:

1. Is this workflow used frequently in production?
2. Does failure block revenue, compliance, security, or customer operations?
3. Has this area caused escaped defects before?
4. Does this test cover a critical integration point?
5. Does it validate permissions or data integrity?
6. Does it detect real regressions, or mostly duplicate other tests?
7. Is it stable enough to support release decisions?
8. Is the same behavior already covered at API, unit, or component level?

Example scoring model:

record RegressionValue(
    String testName,
    int businessCriticality,
    int productionUsage,
    int escapedDefectHistory,
    int customerImpact,
    int integrationRisk,
    int flakinessCost
) {
    int score() {
        return businessCriticality
            + productionUsage
            + escapedDefectHistory
            + customerImpact
            + integrationRisk
            - flakinessCost;
    }
}

RegressionValue test = new RegressionValue(
    "approveHighValuePurchaseRequest",
    5,
    4,
    4,
    5,
    4,
    1
);

Assertions.assertTrue(test.score() >= 15);

High-value Playwright tests usually validate end-to-end user-visible outcomes. For example, a payment test should not only check that the Pay button is visible. It should verify that payment succeeds, the order status changes, the confirmation is shown, and the user can see the final result.

Once identified, these top-value tests should be kept fast, stable, owned, and reviewed carefully. They are good candidates for PR smoke, pre-release validation, or deployment gates. Lower-value tests can run nightly, be moved to API/component layers, consolidated, or removed if they duplicate stronger coverage.

This review should be repeated periodically because product risk changes over time. A workflow that was critical during rollout may become stable later, while a new module, integration, or customer-specific feature may become more important.

Common mistake: choosing the critical regression suite only because tests are fast, without checking whether they protect high-risk workflows, customer impact, production usage, permissions, integrations, or historically defect-prone areas.



Question 1.11

What principles would you follow for risk-based release automation with Playwright Java?

Interview-Style Answer

I would design risk-based release automation around release confidence, not just test volume. The focus should be on critical business workflows, production-like integration coverage, clear failure evidence, controlled edge-case simulation, and fast feedback for release decisions.

In Playwright Java, I would prioritize high-risk journeys such as login, checkout, payment, order creation, approval flows, role-based access, and customer-facing regression areas. These flows should run against real backend services where release confidence depends on integration behavior, while page.route() or browserContext.route() can be used carefully for rare edge cases, error responses, or hard-to-create states.

Detailed Explanation

Risk-based release automation should answer one main question: “Do we have enough confidence to release this build safely?”

The suite should not simply run the maximum number of tests. It should run the right tests at the right stage of the pipeline. High-risk, high-impact flows should be given priority because failures there can block users, affect revenue, break compliance, or damage customer trust.

Key principles:

1. Prioritize business-critical workflows.
2. Cover high-risk integrations with real backend behavior.
3. Use controlled mocks only for specific edge cases.
4. Validate visible user outcomes, not only technical events.
5. Keep release tests stable, fast, and maintainable.
6. Capture trace, screenshot, video, console logs, and network evidence for failures.
7. Classify failures before making release decisions.
8. Treat flaky tests as release risk, not as harmless noise.
9. Separate smoke, critical regression, full regression, and exploratory coverage.
10. Review escaped defects and add or improve coverage based on real production risk.

For example, a release smoke suite may verify that a buyer can log in, search for a product, place an order, and see the confirmation message. The test should validate user-visible results such as order number, confirmation status, updated dashboard, or email trigger indicator, not just that an API returned 200.

page.getByRole(AriaRole.BUTTON,
    new Page.GetByRoleOptions().setName("Place Order")
).click();

PlaywrightAssertions.assertThat(
    page.getByText("Order placed successfully")
).isVisible();

PlaywrightAssertions.assertThat(
    page.getByTestId("order-number")
).isVisible();

For rare scenarios, such as payment service timeout or inventory API failure, mocking may be appropriate:

page.route("**/api/inventory/**", route ->
    route.fulfill(new Route.FulfillOptions()
        .setStatus(503)
        .setContentType("application/json")
        .setBody("{\"message\":\"Inventory service unavailable\"}"))
);

page.navigate(baseUrl + "/checkout");

PlaywrightAssertions.assertThat(
    page.getByText("Inventory service unavailable")
).isVisible();

The release decision should be based on risk signals such as failed critical flows, flaky-test trends, defect history, changed modules, failed integrations, environment instability, and quality of failure evidence. A 98% pass rate is not enough if the failed 2% includes checkout, payment, login, or approval workflows.

Common mistake: treating risk-based release automation as running the largest possible suite before release. A better approach is to run a focused, stable, evidence-rich suite that protects the most important user journeys and gives stakeholders clear release risk information.


Ready to prepare with the complete 1800+ question ebook?

Buy the Full Ebook