DEV Community

Jenni Juli
Jenni Juli

Posted on

Playwright Advanced Interview Questions

  1. What are the benefits of using Playwright over Selenium?
    Playwright offers auto-waiting, handling of single-page applications, and built-in support for multiple browsers including WebKit. It has better support for modern web features and provides context isolation to test parallel sessions. Its API is generally faster and more reliable due to reduced flakiness. Playwright also supports network interception, tracing, and video recording out of the box. Overall, it is more modern and developer-friendly than Selenium.

  2. How does Playwright handle multiple browser contexts?
    Playwright allows creating multiple browser contexts in a single instance, enabling parallel test execution within the same browser process. Each context is isolated, so cookies, localStorage, and sessionStorage do not overlap. This helps simulate different users or environments in parallel. It improves performance by avoiding multiple browser launches. It’s particularly useful for complex end-to-end scenarios involving multiple users.

  3. Explain the difference between page.waitForSelector() and page.locator().
    page.waitForSelector() is an explicit wait that pauses test execution until the selector is visible or attached to the DOM. page.locator(), introduced later, offers lazy evaluation: it fetches elements dynamically when used, supporting actions like click and fill without explicitly waiting. Locators reduce test flakiness by automatically handling waits internally. They also support scoping and filtering, making them more flexible. Using locators is now the recommended approach in Playwright scripts.

  4. How do you handle file uploads in Playwright?
    Playwright supports file uploads through the page.setInputFiles() method. You first locate the file input element and then call setInputFiles() with the path to your file. It works seamlessly with both visible and hidden file inputs. You can also set multiple files at once by passing an array of file paths. This method bypasses manual clicking, ensuring reliable and fast uploads during automation.

  5. Describe how to record and view trace in Playwright.
    To record traces, you enable tracing via context.tracing.start() before test steps and context.tracing.stop() after. Playwright generates a trace.zip file that captures network logs, DOM snapshots, and actions. You can view it using the Playwright Trace Viewer, either locally or in CI/CD. Traces help debug failures by visually replaying what happened. They’re powerful for troubleshooting flaky or complex test cases.

  6. Can Playwright intercept and mock network requests? How?
    Yes, Playwright can intercept and modify HTTP requests and responses using route interception. With page.route(), you define a callback that can abort, fulfill, or continue a request. You can mock APIs, test offline scenarios, or simulate slow networks. It’s useful for isolating frontend tests from backend services. This feature greatly enhances test stability and control over external dependencies.

  7. What is auto-waiting in Playwright and why is it important?
    Auto-waiting means Playwright automatically waits for elements to be actionable before performing actions like click or fill. It waits for conditions like visibility, stability, and enabled state. This reduces the need for explicit waits, making tests faster and less flaky. Auto-waiting adapts to dynamic UI changes, essential for modern web apps. It’s a major advantage over traditional polling or fixed sleeps.

  8. How do you perform visual testing using Playwright?
    Visual testing in Playwright typically involves taking screenshots using page.screenshot() and comparing them against baseline images. For better workflows, you integrate tools like Percy or Applitools, which handle diffing and reporting. You can capture full-page or element-specific screenshots. Visual testing ensures UI consistency after code changes. Playwright also supports capturing videos for test runs to aid debugging.

  9. What are browser contexts and why are they useful?
    Browser contexts are isolated sessions within a single browser instance, each with its own cookies, localStorage, and sessionStorage. They’re useful for testing multi-user scenarios without launching separate browsers. Contexts improve test speed by avoiding repeated browser startups. They help simulate real-world cases like different user roles interacting. Playwright’s efficient context management boosts parallel execution.

  10. Explain the role of selectors and how to choose effective ones.
    Selectors help identify elements on a page. In Playwright, you can use CSS, text, XPath, or custom selectors like data-testid. Effective selectors should be stable, descriptive, and resilient to UI changes. Prefer data attributes over dynamic class names. Playwright’s locator API supports combining and chaining selectors, improving reliability. Choosing the right selector strategy reduces test maintenance.

  11. What is Playwright Test Runner and why should you use it?
    Playwright Test Runner is an integrated framework for running tests, offering features like parallelism, retries, fixtures, and reporters. It simplifies setup by including Playwright dependencies and recommended practices. Built-in features like trace generation, HTML reporting, and test isolation improve debugging and CI integration. It’s tailored to Playwright, removing the need for third-party test runners. It enhances productivity for modern end-to-end testing.

  12. How can you debug Playwright tests?
    Playwright offers several debugging tools: running tests in headed mode, adding page.pause() to open the inspector, and using browser developer tools. You can also generate traces or videos to replay failed tests. Running with DEBUG=pw:api logs API calls for deeper insights. Combining these tools helps quickly identify and fix issues. Debugging is a seamless part of the Playwright workflow.

  13. Describe how to implement parallel test execution in Playwright.
    Playwright Test Runner supports parallel execution by default across files. You can control concurrency using the workers option in the config file. Within a test file, each test runs in a separate browser context for isolation. Parallelism improves execution speed, especially for large suites. Careful test design avoids shared state to prevent flaky results. Efficient use of workers balances speed and resource usage.

  14. What are fixtures in Playwright?
    Fixtures are reusable components that set up and tear down resources for tests, like browser contexts, pages, or test data. Playwright Test includes built-in fixtures and allows custom fixtures to share setup across tests. Fixtures improve code organization and reduce duplication. They can have scopes like test or worker to manage lifecycle. Using fixtures leads to cleaner and maintainable test code.

  15. How do you handle authentication in Playwright tests?
    Common approaches include programmatically logging in during test setup or reusing stored authentication state. Playwright supports saving browser storage to a file using context.storageState() and restoring it later. This speeds up tests by skipping repetitive logins. You can also use API requests to create sessions directly. Managing auth properly improves test speed and reliability.

  16. Explain how to test APIs using Playwright.
    Playwright includes an APIRequestContext to send HTTP requests directly, supporting GET, POST, PUT, DELETE, and more. You can test backend endpoints, validate responses, and set up test data. It complements UI testing by covering backend scenarios. Tests can mix UI and API calls for end-to-end coverage. API testing in Playwright is fast, avoiding browser overhead.

  17. What are test retries and why use them?
    Test retries rerun failed tests a specified number of times before marking them as failed. They’re useful to handle flaky tests caused by network latency, animations, or timing issues. Playwright Test supports retries at the test or suite level. While retries shouldn’t mask real issues, they improve CI stability. Retries help maintain green builds without skipping tests.

  18. How do you capture videos of test runs?
    Playwright can capture videos by enabling video recording in the browser context options. Videos record the entire test execution and are saved automatically for failed tests if configured. They help diagnose why a test failed by visually replaying steps. Videos complement logs, screenshots, and traces. This feature is invaluable for debugging non-reproducible issues in CI.

  19. Describe handling dynamic content in Playwright tests.
    Playwright’s auto-waiting and locators handle dynamic content gracefully by waiting for visibility or stability. You can also use explicit waits like waitForSelector() or waitForResponse() for complex scenarios. Avoid fixed sleeps to reduce flakiness. Testing dynamic apps requires careful selector strategies and synchronization. Playwright’s built-in waiting model simplifies this process.

  20. What is the role of test reporters in Playwright?
    Test reporters generate human-readable summaries of test execution. Playwright Test supports built-in reporters like list, dot, HTML, and JSON. They show passed, failed, and skipped tests, plus error messages. Custom reporters can integrate with dashboards or CI/CD tools. Good reporting helps teams quickly understand test results and debug failures. HTML reports also include traces and screenshots for richer insights.

  21. How do you handle pop-ups or dialogs in Playwright?
    Playwright handles dialogs with the page.on(‘dialog’) event. You register a listener to accept, dismiss, or retrieve dialog text. You can also use page.once() for a single dialog. Handling pop-ups requires synchronizing the triggering action and dialog handling. Playwright ensures dialogs don’t block test execution. This feature is critical for testing alert, prompt, and confirm dialogs.

  22. Explain the concept of test isolation and why it matters.
    Test isolation ensures each test runs independently, avoiding shared state that causes flaky tests. Playwright achieves this by running tests in separate browser contexts or processes. Isolation prevents data leaks between tests, ensuring reliable and repeatable results. It’s especially important for large suites or parallel execution. Proper isolation keeps tests maintainable and predictable.

  23. How do you deal with slow-loading pages in Playwright?
    Playwright’s auto-waiting helps, but you can adjust navigation and action timeouts using page.setDefaultNavigationTimeout() or page.setDefaultTimeout(). You can also explicitly wait for networkIdle or specific elements. Monitoring performance with traces helps identify bottlenecks. Avoid relying on fixed delays, which slow tests unnecessarily. Balancing waits improves test reliability and speed.

  24. Can Playwright handle mobile emulation? How?
    Yes, Playwright can emulate mobile devices using browser.newContext() with device descriptors from playwright.devices. It sets user agent, screen size, and touch support. You can simulate different phones and tablets to test responsive designs. Playwright doesn’t run on real devices but emulates the environment accurately. This helps ensure apps work correctly on various devices.

  25. What are some best practices for writing maintainable Playwright tests?
    Use locators over raw selectors, keep tests short and focused, and reuse code via fixtures and helper functions. Store authentication state to avoid repeated logins. Add meaningful assertions and clear error messages. Regularly refactor tests to remove duplication. Following these practices reduces flakiness, speeds up execution, and keeps tests readable and maintainable.

Top comments (0)