Playwright Api Overview
Playwright is an open-source automation framework developed by Microsoft for end-to-end testing of web applications. It supports multiple programming languages, including JavaScript, TypeScript, Python, C#, and Java. Playwright allows for automated testing across all modern browsers—Chromium, Firefox, and WebKit. It is designed to enable reliable testing, with features like auto-waiting for elements, capturing screenshots, and generating detailed test reports. Its capabilities include browser automation, page interaction, handling multiple browser contexts, and more, making it a versatile tool for web testing and automation.
PlayWright Testing Interview Q & A
1. What is Playwright?
Playwright is an open-source framework for web automation and end-to-end testing. And is developed by Microsoft.
2. Between Playwright and selenium which tool to use and why?
- Browser Support : Playwright is designed to test modern web apps, supporting all modern rendering engines (Chromium, WebKit, and Firefox). It handles complex scenarios involving multiple tabs, frames, and web workers efficiently. Selenium supports various browsers like Chrome, Firefox, Safari, Internet Explorer, Edge, and Opera. It is ideal for testing across multiple browsers, including older versions., Internet Explorer, Edge, and Opera. It is ideal for testing across multiple browsers, including older versions.
- Language Support: Playwright supports Java, C#, Python, TypeScript and JavaScript. Where as Selenium supports multiple languages such as Java, C#, Python, Ruby and Javascript.
- Performance and Speed: Playwright generally offers faster execution times due to its headless mode and efficient handling of browser instances. Playwright’s ability to run tests in parallel using multiple browser contexts can significantly speed up test suites. Selenium: Can be slower, especially when running in a non-headless mode or when dealing with network latency in WebDriver communication. Selenium Grid can be used for parallel execution, but it requires additional setup and infrastructure.
- Features and Capabilities: Playwright supports advanced features like network interception, allowing testers to mock network responses, monitor network activity, and more. It also has built-in support for handling multiple tabs, frames, and browser contexts, making it easier to simulate complex user scenarios. Playwright’s architecture is designed to support headless browsing, making it efficient for CI/CD pipelines.While Selenium supports basic network interception through third-party tools or browser plugins, it does not natively support this feature. Selenium’s handling of multiple windows, frames, and alerts requires more boilerplate code and can be less intuitive. However, Selenium’s extensive community support and documentation can help overcome these limitations.
-
Community and Ecosystem: Playwright is relatively newer tool with a growing community. It is developed by Microsoft and has a strong focus on modern web technologies. While its ecosystem is expanding, it may not have as many third-party integrations and plugins as Selenium. Selenium is a well-established tool with a vast ecosystem, including a wide range of plugins, integrations, and community support. Selenium has been around for over a decade, making it a trusted and reliable choice for web automation.
- Playwright provides a modern, developer-friendly API with built-in auto-waiting mechanisms. This means Playwright automatically waits for elements to be ready (e.g., visible, clickable) before interacting with them, reducing the need for explicit waits and improving test reliability.
Playwright and Selenium both offer robust capabilities for web automation, but they cater to slightly different needs. Playwright excels in modern, cross-browser testing with advanced features, while Selenium remains a reliable and well-supported choice for a broader range of web automation tasks. The choice between them often depends on the specific requirements of the project, the existing technology stack, and the team’s familiarity with the tools.
3. What are the limitations of Playwright?
Playwright doesn’t support Mobile automation (They might introduce it in the future)
Limited Support for Older Browsers: Playwright doesn’t support legacy IE Automation
Less Extensive Language Support: Although Playwright supports JavaScript/TypeScript, Python, C#, and Java, its language support is not as broad as Selenium, which also supports Ruby, PHP, and Perl, among others.
Performance Overhead: Playwright’s cross-browser support, especially for non-Chromium browsers (like Firefox and WebKit), can sometimes introduce performance overhead. Additionally, Playwright’s feature-rich nature can lead to increased resource usage compared to simpler tools.
Rapid Evolution and API Changes: As Playwright is still under active development, its API can change more frequently than more established tools like Selenium. This rapid evolution can sometimes lead to breaking changes or the need for frequent updates to test scripts.
4. Which languages are supported by Playwright?
Playwright supports the following programming languages.
- JavaScript
- TypeScript
- Python
- C#
- Java
5. Name the browsers supported by Playwright.
- Chromium – includes Google Chrome and Microsoft Edge, as they are both based on the Chromium engine.
- Firefox
- WebKit – this engine is used by Safari on macOS and iOS
6. Can I run playwright tests on InternetExplorer?
Playwright does not support Internet Explorer (IE). Internet Explorer is an outdated browser, and many modern web automation tools, including Playwright, do not provide support for it. Instead, they focus on supporting the latest versions of modern browsers like Chromium, Firefox, and WebKit.
If you need to test applications on Internet Explorer, you might consider using other tools like Selenium, which still provides support for IE through the Internet Explorer Driver.
7. Imagine you want to open the Gmail login page, enter your username and password, and then submit the login form. Assuming Playwright is already installed and your project is set up, can you explain the steps involved in accomplishing this task?
- Create a playwright object and launch browser.
- Playwright.create()
- browser = playwright.chromium().launch(…). You can also use playwright.firefox() or playwright.webkit() to launch Firefox or WebKit browsers.
- Using browser object create above create Browser context and page objects
- context = browser.newContext()
- page = context.newPage() – Opens a new tab in the browser
- Using page object created, navigate to login page and interact with page elements using page object
- page.navigate(“https://example.com”)
- page.locator(“locator identifier”).fill(“text to enter”)
- page.click(…)
- we can also use page.title() to check if we are on the right page.
- Finally close the browser – browser.close()
8. What is the purpose of using a browser context in Playwright, and how does it differ from a browser instance?
A browser context in Playwright provides an isolated environment within a browser instance. It allows multiple sessions with separate cookies, cache, and local storage, enabling parallel testing of different scenarios (e.g., multiple user logins) within the same browser instance. This is more efficient than launching multiple browser instances.
9. Describe a scenario where using multiple browser contexts in Playwright would be advantageous.
Multiple browser contexts are useful when testing multiple user scenarios in parallel, such as testing different users with different roles and permissions. Each context can have its own session data, preventing interference and allowing isolated tests within the same browser instance.
10. How do you navigate to a specific URL in Playwright?
Can use either page.navigate(…) or page.goto(…).
11. Between navigate and goto methods which one is preferred for navigating to specific URL?
there is no difference between navigate
and goto
in Playwright; page.goto()
is the method you should use for navigating to a URL. It provides options to wait for specific load states, making it a flexible and powerful tool for handling navigation in your automated tests.
12. What are the different types of reports playwright supports?
Playwright supports HTML, JSON, JUnit XML, list, dot, line, Allure, and custom reporters. Depending on your requirements, you can configure Playwright to generate one or multiple types of reports simultaneously by specifying them in the Playwright configuration file.
13. What is an element locator?
Its a way to identify and interact with specific elements on a webpage. It uses selectors like CSS selectors, XPath, text content, and more to locate elements.
14. What are the different ways to locate the elements?
- CSS Selectors – CSS selectors are one of the most common ways to locate elements in Playwright. They are powerful and flexible for targeting elements based on their class, id, attributes, and hierarchical relationships.
- Locator element = page.locator(“button.submit”); // By class
- Locator element = page.locator(“#username”); // By id
- Locator element = page.locator(“input[name=’email’]”); // By attribute
- Locator element = page.locator(“div > span.child”); // By hierarchical relationship
- Text Selectors – You can locate elements by their text content using the
text=
prefix.
- Locator element = page.locator(“text=Submit”); // Exact text match
- Locator element = page.locator(“text=Submit”, new Locator.LocatorOptions().setExact(false)); // Partial text match
- XPath Selectors – XPath selectors allow you to locate elements using XML path expressions. This method is useful when dealing with complex XML structures or when CSS selectors are not sufficient.
- Locator element = page.locator(“//button[@class=’submit’]”); // By attribute
- Locator element = page.locator(“//div[contains(text(), ‘Submit’)]”); // By text content
- Role Selectors – Role selectors allow you to locate elements by their ARIA roles, names, and attributes, which is useful for accessibility testing.
- Locator button = page.locator(“role=button[name=’Submit’]”); // By role and name
- Locator checkbox = page.locator(“role=checkbox[checked]”); // By role and attribute
- PlaceHolder Text – You can locate input elements by their placeholder text using the
placeholder
prefix.
- Locator input = page.locator(“placeholder=Enter your name”); // By placeholder text
- Alt Text – Locate image elements by their alt text using the
alt
prefix.
- Locator image = page.locator(“alt=Company Logo”); // By alt text
- Label Text – You can locate form elements by their associated label text using the
label
prefix.
- Locator input = page.locator(“label=Username”); // By label text
- Test ID Attribute – Custom data attributes, like
data-test-id
, are commonly used in testing to provide stable and reliable selectors.
- Locator element = page.locator(“[data-test-id=’unique-id’]”); // By custom attribute
- Chaining locators – You can chain locators to narrow down the search to child elements relative to a parent element.
- Locator parent = page.locator(“div.parent”);
- Locator child = parent.locator(“span.child”); // Child element relative to the parent
- Index based selectors – Select elements based on their index among siblings using the
nth
method.
- Locator thirdItem = page.locator(“li.item”).nth(2); // Select the third item (0-based index)
- Contains Text – Locate elements that contain specific text using the
has-text
prefix.
- Locator element = page.locator(“has-text=’Click me'”); // Contains specific text
15. How do you enter text into an input field in Playwright?
You can enter text into an input field using the fill()
method.
16. How do you click a button in Playwright?
You can click a button using the click()
method.
17. How do you check a checkbox in Playwright?
You can check a checkbox using the check()
method. click()
method also can be used but before click()
method, we should check if the checkbox is not checked using isChecked()
method and then click.
18. How do you select an option from a dropdown in Playwright?
You can select an option from a dropdown using the selectOption()
method.
19. How do you get the text content of an element in Playwright?
ou can get the text content of an element using the textContent()
method.
20. How do you handle dynamic content in Playwright?
- By ensuring elements are present and interactable before performing actions – auto-wait features or explicit waits like
page.waitForSelector()
- By using right locator identification if element id or name is changing and not constant across refresh
21. How would you handle an element that may not be immediately available on the page when performing an action in Playwright?
In Playwright, you can use built-in methods like waitForSelector
to wait for an element to appear before interacting with it. This ensures that the script does not throw an error due to the element being absent or not yet rendered.
22. When do use waitForNavigation
?
waitForNavigation
method is used to wait for the page to navigate to a new URL. It is commonly used after actions that cause navigation, such as clicking a link or submitting a form, to ensure that the subsequent code executes only after the new page has loaded.
23. How can you handle navigation to a new tab or window in Playwright?
context.waitForPage() – wait for new tab or page to open and lets say it returns “newPage” object
newPage.waitForLoadState()
– for page to load
newPage object can be used to perform actions on new tab
24. How would you capture a screenshot of a specific element or the entire page in Playwright using Java?
Using screenshot method of page object. page.screenshot
25. How do you handle multiple tabs in Playwright?
context.newPage() opens a new tab (page) within the same browser context. Each call returns a new Page
object, which can be used to interact with the new tab. we can switch between the tabs or do interactions on the tab using relevant page object reference.
if we want to have each tab in isolation like not sharing session data and cookies then we can use different browser context while creating new page for new tab.
26. When should you browser.close() ?
The browser.close()
method closes the browser instance, terminating all open tabs, browser contexts, and associated processes. It is used to clean up resources and end the Playwright session. And is used at the end of a test or script to ensure that all resources are properly released. It is particularly important in a testing environment to avoid leaving orphaned browser processes running, which can consume system resources.
27. What happens if we don’t call browser.close()
at the end of the tests?
unclosed browser processes, leading to unnecessary consumption of system memory and CPU. This can slow down the system and potentially interfere with other automated tasks or tests.
28. What is the difference between browser.close()
and context.close()
?
browser.close()
closes the entire browser instance along with all its contexts and pages. In contrast, context.close()
only closes a specific browser context, along with all the pages within that context, without affecting other contexts or the browser instance itself.
29. Is it necessary to call browser.close()
when running tests in headless mode?
Yes, it is necessary to call browser.close()
in both headless and non-headless modes to properly terminate the browser process and free up system resources. Headless mode does not automatically close the browser when the script ends, so explicit closure is required.
30. How can you ensure that browser.close()
is always called, even if an exception occurs during test execution?
By adding browser.close()
in try-finally
block or by registering it in a shutdown hook, We can ensure that it is executed regardless of whether an exception occurs during the test.
31. In a multi-threaded environment, what precautions should be taken when calling browser.close()
?
In a multi-threaded environment, it is important to ensure that browser.close()
is not called while other threads are still interacting with the browser. Proper synchronization and coordination between threads are necessary to avoid race conditions and ensure that all tests or interactions are completed before the browser is closed.
32. What are the different waits available in Playwright?
- Auto Wait, Playwright automatically waits for elements to be actionable before performing actions like clicking or filling forms.
- Explicit Wait, we can specify for certain condition to happen on an element, page or event.
- Navigational waits which waits for the page to navigate to a new URL or reload.
page.waitForNavigation([options])
- Element Handle Waits which waits for an element to reach a specific state, such as ‘visible’ or ‘enabled’.
elementHandle.waitForElementState(state[, options])
- Frame Waits which waits for an element within a frame to appear in the DOM.
frame.waitForSelector(selector[, options])
33. What is implicit wait in playwright and how to use?
Playwright does not support implicit waits. It uses explicit waits and built-in auto-waiting mechanisms.
34. What’s the difference between autowait and explicit wait?
Auto-waiting in Playwright is an implicit waiting mechanism built into the API that automatically waits for certain conditions to be met before performing actions such as click
, fill
, or hover
. Conditions Covered in auto wait are Presence in DOM, visibility, enablement and stable state. So we really don’t need waitForSelector on the same element here. But in situations like I want to click on some element but before that I want to see some other element is present in this case we use waitforselector on element1 and then click on element2.
page.waitForSelector(selector)
is an explicit waiting method that pauses the script until an element matching the selector appears in the DOM or meets specified conditions. Conditions covered here are presence in DOM and Custom States: Can wait for specific states like ‘visible’, ‘hidden’, ‘attached’, or ‘detached’.
35. How do you wait for a page to load completely in Playwright?
page.waitForLoadState('load')
is used
36. What is the purpose of the page.waitForTimeout()
method?
The page.waitForTimeout()
method pauses the execution of the script for a specified amount of time, given in milliseconds. It is often used for debugging or for introducing delays in the execution flow.
37. Is it a good practice to use page.waitForTimeout()
?
It is not a good practise using page.waitForTimeout()
for synchronization purposes, as it can lead to flaky tests and unnecessary delays. Instead, use more precise waiting methods like waitForSelector
or waitForFunction
to wait for specific conditions.
38. What are some alternative methods to page.waitForTimeout()
for waiting for elements or conditions in Playwright?
You can use page.waitForSelector()
, page.waitForLoadState()
, page.waitForFunction()
, and page.waitForEvent()
, which wait for specific conditions like element appearance, page load state, custom JavaScript conditions, and events, respectively.
39. How does playwright handles file upload?
page.setInputFiles("input[type='file']", "/path/to/file.txt")
:
we can upload file by setting the file path for the file input element. Replace "/path/to/file.txt"
with the actual path of the file you want to upload.
40. How do you handle browser downloads in Playwright?
We can set up a listener for the download event in playwright using page,onDownload(…). And then performing actions based on the download object.
download object has different methods to perform on the download event like
download.cancel() – cancels download
download.url() – get the url from where the download is initiated.
download.delete() – deletes downloaded file
download.failure() – returns the error occurred while download failure happenes
download.path() – Returns the file path to the downloaded file. This method waits for the download to finish
download.saveAs(path) – Saves the file in the given path
download.suggestedFilename – Returns the suggested filename for the download.
41. Why can’t we use page.type() with file path and selector?
The page.type()
method cannot be used with file inputs due to browser security restrictions that prevent direct text input into file paths. Instead, Playwright provides the setInputFiles()
method to safely and effectively handle file uploads. This method sets the file path programmatically, ensuring secure and correct interaction with the file input element.
42. How do you check if an element is visible in Playwright?
page.isVisible()
returns true or false based on element is visible or not.
43. What potential issues might arise when checking for element visibility and how can you mitigate them?
There can be timing problems where the element may not be immediately visible due to dynamic content loading. To mitigate this, you can use waitForSelector
to ensure the element becomes visible before interacting with it, and handle timeouts and exceptions gracefully.
44. How do you execute JavaScript within a Playwright test?
We can use page.evaluate()
method to execute custom JavaScript code within the context of a page. This is useful for interacting with elements or retrieving values directly from the DOM.
45. How do you write parameterized tests in Playwright using Java?
In Java, parameterized tests can be written using testing framework we are using like JUnit, TestNG or Cucumber. Suppose in JUnit @ParameterizedTest is used. in TestNg, @DataPrivider annotation is used. In Cucumber, Examples and Scenario outline is used to run the same tests for multiple data.
46. How do you handle timeouts in Playwright?
You ca set the timeout
option in actions like page.goto()
, locator.click()
, or globally using page.setDefaultTimeout()
.
47. What are the benefits of using headless mode in Playwright?
Headless mode allows tests to run faster and consume fewer resources since no GUI is rendered. It’s ideal for CI environments where visual output is unnecessary.
48. What are the ways to execute tests in parallel using Playwright?
Execute tests in parallel by configuring the workers
option in playwright.config.js
, leveraging multiple BrowserContext
s, or running tests in parallel on different devices or browser types.
49. How can you handle multiple environments in Playwright tests?
By using environment variables or separate configuration files in playwright.config.js
, and dynamically setting base URLs, credentials, and other settings.
50. How do you perform cross-browser testing in Playwright?
We can do this by creating separate test runs, parameterize the browser name and pass it through configuration
51. How do you handle scrolling in Playwright?
We can use locator.scrollIntoViewIfNeeded()
to bring an element into view or use page.evaluate()
with JavaScript to perform custom scrolling actions.
52. How can you test localization in Playwright?
By setting different locale
options in BrowserContext
, changing language settings in the browser, and validating that UI elements render correctly in different languages.