“UI Automation Testing using Playwright with Java”
In this blog, we will explore playwright and will see that how UI automation testing can be done using Playwright with Java.
Introduction to Playwright
Playwright is open source test automation library which is initially developed by Microsoft.
It supports multiple browsers like Chromium, Firefox, Web kit. It supports multiple languages like Typescript, JavaScript, Java, Python, .NET, C# and also it supports multiple platforms like Windows, Linux, mac OS, Android, iOS.
Playwright aims to provide fast, reliable, and user-friendly automation capabilities for testing web applications. It provides wide range of features that makes it useful for variety of tasks.
There are three main components of playwright :
- The browser driver — It is responsible for controlling the browser engine and executing commands from the playwright API.
- The browser context — Represents a single instance of a browser, with its own cookies, cache and other settings. Playwright supports multiple browser context within the same browser instance, which can be used for separate sets of tests or scenarios And each browser context has its own set of pages.
- The page — Represents a single web page within a browser context with its own DOM tree, frame hierarchy and other content.
Example test :
When writing tests with Playwright, it offers “assertThat” overloads that intelligently wait until the expected condition is met.
There is list of assertions such as:
.isChecked(), .isEnabled(), .isDisabled(), .isEditable(), .isVisible() & many more are there.
Locators play a crucial role in Playwright’s auto-waiting and retry mechanism, enabling efficient element identification on web pages. They provide a means to locate elements and perform various actions like click(), fill(), and many more. Additionally, Playwright allows the creation of custom Locators using the “page.locator()” method.
Also playwright provides multiple actions, example ->
•To input text it provides fill() method,
•For checkboxes and radio buttons it provides setChecked(),
•For selecting one or multiple options it has selectOptions(),
•For clicking it has click(), dblClick() methods,
•It provides method called type which enters string character by character and many more are there.
Playwright offers several features that make it an excellent choice for UI automation testing.
These features include:
1.Auto-waiting:
Playwright performs thorough checks on elements to ensure that actions behave as expected. It automatically waits for all necessary conditions to be met before executing the requested action. If the required conditions are not met within the specified timeout, the action fails. This approach guarantees that actions are performed at the right time, enhancing the reliability and accuracy of UI automation.
For example: If we want to perform click() action on an element then playwright ensures that
- An element is attached to the DOM or not
- Element is visible or not
- It is stable or not
- It is enabled and it receives event or not
And after performing all required checks it performs the click action.
2.Headless and Non-headless mode:
Run your automated tests in headless mode or non-headless mode.
3.Debugging Tests:
The Playwright Inspector is a graphical user interface (GUI) tool that facilitates debugging of your Playwright tests. It allows you to live-edit locators, pick locators, and view logs. Additionally, you can utilize the “page.pause()” method to debug your test cases effectively. This approach eliminates the need to manually navigate through each test action to reach the desired debugging point, streamlining the debugging process.
4.Test Generator:
Playwright includes a powerful test generation feature that allows you to perform actions in the browser. Playwright figure out the best locator at page, for that it prioritize role, text and testid locators.
If the test generator discovers multiple elements that match the same locator, it enhances the locator to ensure uniqueness, enabling us to accurately identify each element.
Command : mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args=”codegen demo.playwright.dev/todomvc”
When running the Codegen command two windows will get opened, a browser window to interact with page element and playwright inspector to record a tests.
5.Emulation:
We can use test generator to generate tests using emulation, So we can generate a test for a specific viewport size, specific device or specific color scheme, also we can emulate geolocation, language or time Zone.
First let’s see emulate viewport size:
Playwright allows you to open a browser window with a specific width and height by using the “viewport” option. This feature enables you to generate tests with different viewport sizes, providing flexibility in emulating various screen resolutions and responsive designs.
Command : mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args=”codegen — viewport-size=800,600 playwright.dev”
- Emulate Device:
we can use command mentioned below:
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args=’codegen — device=”iPhone 13" playwright.dev’
In command we can use — device option which sets the viewport size and user agent.
We can also write a script for this:
Playwright provides a useful feature to emulate different devices and their characteristics, allowing you to test your web application’s behavior on various devices without needing the physical device. You can use the “setViewportSize” and “setUserAgent” methods to emulate the device properties. Here's an example:
6.Intercepting Network request
Playwright offers a powerful feature that enables us to seamlessly modify or block network requests initiated by a web page. This can be useful for testing purposes like simulating slow network conditions or mocking server responses or testing behavior of the web application under certain condition.
Example:
So in this example, we are setting up a network route for the requested URL, the lambda expression is called when matching request is made. We are setting custom message , status code, content type , body as our custom message.
Because we have set up a network route for the URL, our custom response will be returned instead of the regular page content as shown below:
7.Accessibility Testing
Accessibility testing is an important aspect of ensuring that a web application is usable for all users, including those with disabilities. Playwright provides built-in support for performing accessibility testing.
8.Authentication
Playwright provides an isolated environment called the browser context for executing tests. This allows tests to load an existing authenticated state, eliminating the need to log in for each test. By saving the authentication state in the context, it can be reused across all tests. This approach saves time by avoiding redundant login operations and ensures complete isolation between independent tests.
9.Downloads
With Playwright’s downloads feature, you can automate the process of downloading files from a website. This feature is useful for testing scenarios that involve verifying the correct download of files, or for automating tasks that involve downloading files. Furthermore, Playwright allows you to customize the behavior of the downloads feature by specifying the download path or filtering the types of files that can be downloaded.
10.Trace Viewer
The Playwright trace viewer is a tool provided by Playwright that allows you to analyze and visualize the recorded trace data of a browser’s actions during a test execution. Let’s see some of the different options which provides detailed insights into the sequence of events, network requests and other relevant information.
Command: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args=”show-trace”
Actions:
Once the trace is opened in the Playwright trace viewer, you will find a list of actions that were performed by Playwright on the left-hand side. By selecting each action from the list, you can explore detailed information such as the action snapshot, action log, network log, and more.
Metadata:
The Playwright trace viewer offers a comprehensive range of information, including the timing of actions, the browser engine utilized, viewport details, mobile device emulation, and the count of recorded pages, actions, and events.
Screenshots:
Each trace records a screenshot and renders it as a film strip. This film strip provides a visual representation of the recorded actions and states. By hovering over each frame in the film strip, you can view a magnified image that corresponds to a specific action or state, allowing for detailed inspection and analysis.
Call:
Call option includes details such as the action name, the timestamp when it was called, the duration of the action’s execution, the parameters passed to the action, the return value, and any associated log messages.
Console:
The Console panel in Playwright’s trace viewer offers a view of the console output generated during the recorded actions. It allows you to observe console logs, errors, warnings, and other relevant messages produced during the test case execution.
Network:
It provides a view of all network requests made by the browser, along with their corresponding responses, headers, timings, and other relevant information.
Selenium And Playwright
Both are popular choices for web automation testing. There are some key differences.
Architecture:
In selenium each command is transmitted as an individual HTTP request, and the corresponding JSON response is received. Every action performed, such as launching the browser, clicking an element, or entering text into a textbox, is transmitted as a distinct HTTP request. This approach results in the termination of the connection between the server and client, which needed to be re-established for the next request.
Connection termination after each request can lead to slower execution, which introduces a layer of flakiness also.
On the other hand, Playwright utilizes a single web socket connection to handle all requests during the entire test execution. This architectural approach minimizes potential points of failure and enables commands to be transmitted smoothly over a single connection. This makes playwright a more stable tool as compared to selenium.
Speed:
Playwright is faster than selenium when it comes to executing tests, due to its architecture.
Flakiness:
Playwright is designed to be less flaky than selenium again thanks to its architecture that isolates each test in a separate browser context. This means that test do not interface each other reducing the chances of flakiness.
Cross-browser consistency:
Playwright is designed to provide a consistent API across multiple browsers , ensuring that test can be written once and run across different browsers. For selenium, it requires browser-specific drivers, which may cause inconsistencies in behavior and functionality across different browsers.
Debugging:
Both selenium and Playwright provide good debugging capabilities , but playwright provides some additional features that makes debugging easier. Playwright provides an interactive mode that allows you to interact with the browser as test is running which help you to identify issues more quickly.
Testing framework:
Both selenium and playwright can be used with variety of testing frameworks like Jest, Mocha and Jasmine. However playwright has its own test runner, which makes it easier to start with testing without having to learn separate framework.
Conclusion
In conclusion, Playwright combined with Java provides a robust and up-to-date solution for UI automation. Its unified API, ability to work across different browsers, and wide range of features streamline the automation process and improve testing efficiency. The architecture of Playwright, which utilizes browser-specific binaries and maintains persistent web socket connections, guarantees stability and reliability throughout test execution.
For detailed information and additional examples, please refer to the links provided in the references section.