5 Best Practices For Writing & Maintaining Playwright Test Cases

5 Best Practices For Writing & Maintaining Playwright Test Cases

The web applications of today are more powerful and more responsive than ever before, but it is still a challenge to automate the multiple asynchronous events that happen within them. Because of the asynchronous nature of apps, automated testing has become an unreliable method, which explains why many developers and testers have had trouble with this issue. But no worries because Playwright is there for the rescue.

Despite the fact that a lot of frameworks and drivers strive to improve things, they often fall short of the mark when it comes to meeting the requirements of modern web applications.

QA engineers need a framework that keeps pace with the latest techniques for developing web applications. Automated applications should also be able to be started quickly and require as little maintenance as possible. Therefore, modern frameworks should be both robust and easy to use.

The Selenium framework has been the primary testing tool for e2e applications for years. Nevertheless, several other reputable options have now become available – such as Playwright. The primary aim of this blog is to provide information on Playwright automation and its best practices for the creation and maintenance of Playwright tests. So, let’s get started without further ado.

What is the Playwright automation framework?

Playwright is a Node library designed for the creation of e2e testing and automation solutions. Using it will allow for the automated deployment of a number of browsers, including Chromium for Webkit for Safari, Chrome and Edge, and Gecko for Firefox. In addition, it supports multiple programming languages, such as Python, .NET, TypeScript, JavaScript, and Java. Therefore, QA workers can now write test scripts more freely.

Playwright testing enables efficient, consistent, reliable, and effective web automation across browsers. With the framework, powerful and stable automated tests can be written using the DevTools protocol.

A growing number of people are using the Playwright framework. Various trusted sources report that Playwright testing frameworks have been downloaded 644,677 times each week.

How does Playwright test automation work?

There are three distinct layers in the Playwright framework. Let’s examine each layer in more detail:

The first layer creates three platforms for WebKit. Here, Playwright’s testing automation sets up an environment for testing by creating a browser instance.

The second layer consists of browser-specific protocols. The playwright can communicate with different protocols depending on the browser, including the Chrome DevTools Protocol for Chrome and the WebInspector Protocol for Safari. Using Juggler, an addon customized for Gecko, we achieve similar functionality to Chrome DevTools Protocol.

Thirdly, there is the Playwright library layer that provides a single API to manage three different browsers easily.

5 Best Practices For Writing & Maintaining Playwright Test Cases

In playwright, there are some practices that can be used when writing test cases to make the framework more efficient and profitable. In this section, we will examine each of these practices in turn.

1. Prioritize user-facing attributes

It is recommended that, whenever possible, user-facing elements, such as text context, accessibility tiles, and labels, should be used. It is best not to identify elements using “id” or “class.” Use await page.locator(‘text=Login’) rather than await page.locator(‘#login-button’) to locate the login button. A real user would not find the ID but rather the button by looking at the text content.

2. Use locators over selectors

Locators are at the heart of Playwright’s auto-waiting and retry capabilities. A locator can be used to find element(s) on a page at any time.

Your web page will be less likely to break or flake when you use locators. If you use standard selectors, you may not notice any breakages. As an example, instead of using await‘text=Login’), use await page.locator(‘text=Login’).click(). 

With Playwright, you are able to select selectors, ensuring a proper and reliable testing process easily. These are the recommended built-in locators.

a. Locating elements

Several locators are built into Playwright. It is recommended to prioritize user-facing attributes and explicit contracts such as the page.getByRole() when designing tests to make them more resilient.

b. Locate by role

Using the page.getByRole() locator, you can determine whether or not an element on a page is interpreted by users as a button or as a checkbox by assistive technology. It is usually a good idea to pass the accessible name along with the role when you are locating by role so that the locator can pinpoint the exact element you want.

c. Locate by label

It is usually convenient to interact with form controls by using their dedicated labels. By using page.getByLabel(), you can locate the control by its associated label.

d. Locate by placeholder

The placeholder attribute suggests what value the user should enter for an input. This type of input can be located by using page.getByPlaceholder().

e. Locate by text

By looking at the text in an element, you can find it. When using page.getByText(), you can match by substrings, exact strings, and regular expressions.

f. Locate by alt text

A description of the image should be included in the alt attribute of every image. The page.getByAltText() method can locate an image based on the text alternative.

g. Locate by title

In order to locate an element that has the matching title attribute, you will need to use page.getByTitle().

h. Locate by test id

The most resilient way to test is by test id since the test will still pass even if the attribute text or role changes. Developers and QAs should define test ids explicitly and query them with page.getByTestId(). 

However, testing by test ids does not provide a user-facing experience. It is highly recommended that you consider using locators that have a user-friendly interface, such as role and text locators if the role or text value is important to you.

i. Locate by CSS or XPath

The only way you can truly avoid the use of CSS and XPath locators is by using a function called a page. locator(), which enables you to create a locator that accepts a selector that describes where to locate the element on the page. XPath and CSS selectors are supported by Playwright, and they are automatically detected if you omit the CSS or XPath prefixes.

j. Locate in Shadow DOM

Playwright’s locator’s work by default with ShadowDOM elements. The exceptions are:

  • It is not possible to pierce shadow roots when searching by XPath.
  • A shadow root that is in closed mode will not be supported.

3. Use the Page Object Model (POM)

The Page Object Model, or POM, is a design pattern for storing the elements of a website. In addition to reducing code duplication, it improves the maintenance of test scripts. An application’s web pages are each viewed as separate class files in the Page Object Model. The class files will only contain the elements that correspond to the web pages. A tester can use these elements to interact with the website under test. 

Note: POM tests have a better feel as they convey more intent and encourage behavior over pure mechanics.

Advantages of Page Object Model

  • Easy Maintenance: Everything in web automation is dependent on the DOM tree and selectors. Even if we change the DOM tree or selectors, there is no need to modify the entire page object model. 
  • Increased Reusability: The code written for one test can be reused for another test by using POM. This can also be achieved by creating custom helper methods. As a result of code reusability, time and effort are saved.
  • Readability: The tests are independent, which makes them easier to read

Disadvantages of Page Object Model

  • It takes time to design and build a framework from scratch.
  • A good understanding of coding is required to set up the POM framework
  • A tiny error in the page object file can break the entire test suite because elements are held in a shared file.

4. Use double quotes to find specific elements

When you encounter multiple elements in a partial string, use double quotes. As a result, case sensitivity is established. Await Page Locator (‘text=Checkout’), for example, can return both a button and a text if it finds a “Checkout” button and another “Check out this new shoe.” There is also the possibility of finding the button by itself, using await Page Locator (‘text=”Checkout”).

5. Isolation

When tests are written with Playwright, they run in an isolated environment known as a browser context. In this isolation model, test failures are prevented from cascading and improve reproducibility.

What is Test Isolation?

An isolated test is one that is completely separate from another. There is no dependency between any two tests. As a result, each test keeps its own cookies, local storage, session storage, etc. Playwright accomplishes this through BrowserContexts, which can be thought of as incognito profiles. 

These applications can be easily created and are completely isolated, even when executing within a single web browser. Every test is assigned a context, and a default Page is provided as part of that context.

Why is Test Isolation Important?

There is no carryover of failures. The failure of one test does not affect the other.

Debugging errors or flakiness is easy since you can run a single test many times. During parallelization, sharding, etc., there is no need to consider the order of the operations.

Two Ways of Test Isolation

Test isolation can be accomplished in two ways: starting from scratch or cleaning up in between. When it comes to cleaning up, the problem is that it is easy to forget to do it, and some items are impossible to get rid of, like “visited links,” which make it difficult to clean them up in between tests. 

In some cases, the state can leak from one test into the next, resulting in your test failing and making debugging more difficult as the problem may come from another test, which makes the issue harder to tackle. If you start from scratch, you will be working with new code, so if a test fails, you will be able to debug it as long as you look inside that particular test.

How Playwright Achieves Test Isolation

To achieve Test Isolation, Playwright uses browser contexts. There is a separate Browser Context for each test. Each time the test is run, a new browsing context is created. The browser contexts are automatically created when Playwright is used as a Test Runner. Browser contexts can also be created manually.

Role of Tools and Platforms in Playwright Testing

While Playwright is simple, new automated testers may still find it challenging. It is easiest to solve this problem by introducing an effective tool or platform.

Today’s Software Development Industry has thousands of tools and platforms at its fingertips. It is vital that testers make wise decisions in the face of such a large number of choices. The reason for this is that the effectiveness of the tool will play an enormous role in the results of the development project.

In order to better understand this concept, we should consider the example of LambdaTest:

A brief introduction to LambdaTest is that it is an automation testing platform used by developers to ensure that their apps are cross-browser compatible. It allows you to perform Playwright testing at scale across 50+ browser versions on the cloud.

The Takeaway

Automation by playwrights is essential for E2E testing in an era of Continuous Integration and Delivery. Even though it’s a tedious task, following these practices will lead to a better product and less time spent.

About the author


I am a computer science graduate. Started blogging with a passion to help internet users the best I can. Contact Email:

Add Comment

Click here to post a comment