Skip to content

Integrating Custom Test Attributes in HTML for Test Automation

Author: Afsal Backer

Last updated: April 28, 2024

Integrating Custom Test Attributes in HTML for Test Automation
Table of Contents
Schedule

In the realm of web development, ensuring that applications not only meet their functional requirements but are also robust and bug-free is paramount. Test automation frameworks like Cypress, WebdriverIO, Playwright, etc have become indispensable tools in achieving this goal. They simulate user interactions on web pages, verifying that each part of the application behaves as expected. A pivotal aspect of these simulations is the ability to precisely identify and interact with HTML elements. This is where custom test attributes come into play, enhancing the precision and reliability of automated tests.

 

In this article, we will delve into how you can add a specific test attribute to your application's HTML for test automation frameworks. While we'll be shining the spotlight on Playwright—given its stature as a frontrunner in the test automation arena—the insights and methodologies we discuss are universally applicable across the spectrum of sophisticated test automation tools available today.

 

Understanding the Role of Test Attributes

Test attributes are custom HTML attributes that are added to elements specifically for testing purposes. These attributes make it easier to select and interact with elements during automated tests without relying on CSS classes or IDs, which might change as part of the application's styling or functionality updates. The most commonly used test attribute is data-testid, but frameworks like Playwright allow you to configure custom attributes, offering a flexible approach to element selection.

 

Before Adding Custom Test Attribute

Originally, an HTML button might be defined purely based on its functional or stylistic roles, using classes or IDs for styling purposes. For instance:

 

<button class="btn btn-primary" id="navigateButton">Itinerary</button>

 

In this example, the button is identified by a class (btn btn-primary) for styling and an ID (navigateButton) potentially for both styling and basic scripting. However, these identifiers can be somewhat volatile, subject to change with UI updates, and not always unique or descriptive from a testing perspective.

 

After Adding Custom Test Attribute

After deciding to implement custom test attributes for more reliable and descriptive test targeting, the same button element is enhanced as follows:

 

<button class="btn btn-primary" data-testid="button-directions">Itinerary</button>

 

By introducing the data-testid="button-directions" attribute, we've added a stable, purpose-specific identifier that doesn't interfere with styling or existing scripts. This custom test attribute is designed to be used exclusively by test automation frameworks like Playwright, offering a clear, maintainable reference to the element regardless of changes in its styling or structure.

 

Configuring Playwright to Use a Custom Test Attribute

Playwright, by default, uses the data-testid attribute to locate elements. However, it provides a seamless way to configure it to recognize a custom attribute instead. This customization is beneficial for teams with existing conventions or for those seeking to minimize conflicts with other attributes. Here's how you can set it up:

Define the Custom Attribute in the Playwright Configuration:

In your playwright.config.ts, import the defineConfig method from @playwright/test and set the testIdAttribute option to your preferred attribute name. For example, to use data-pw as the test attribute, your configuration would look like this:

 

import { defineConfig } from '@playwright/test';

 

export default defineConfig({

  use: {

    testIdAttribute: 'data-pw'

  }

});

 

Adding the Custom Test Attribute to HTML Elements:


With the configuration in place, you can now modify your custom attribute to any HTML element you wish to control or access through your automated tests. For instance:

<button data-pw="button-directions">Itinerary</button>

 

Locating and Interacting with Elements Using the Custom Attribute:


In your test scripts, you can locate and interact with the elements using the custom attribute just as you would with the default data-testid. Here's how you can click a button with the data-pw="button-directions" attribute:

 

await page.getByTestId('**button-directions**').click();

     

Advantages of Using Custom Test Attributes

  • Clarity and Maintainability: Separating test identifiers from styling and functionality-related attributes or selectors ensures that changes in the UI do not inadvertently break your tests.
  • Flexibility: By allowing custom attributes, frameworks like Playwright accommodate different project conventions and requirements, making it easier to integrate automated testing into existing projects.
  • Consistency: Using a consistent approach to identify elements across tests improves the readability and maintainability of test scripts.

 

Best Practices for Using Test Attributes

  • Use a custom naming convention or meaningful names: Choose attribute values that clearly describe the element's role or function, making it easier for others to understand what the test is targeting.
  • Avoid Overuse: Only add test attributes to elements that you need to interact with in your tests. Overusing them can clutter your HTML and make it harder to read.
  • Collaborate with Developers: Ensure that developers are aware of the test attributes so they can avoid changing them inadvertently during development cycles.

Some examples:

In these examples, we'll employ a prefix that directly indicates the element's type followed by a dash and a purpose-specific descriptor. This naming strategy enhances clarity and aids in the automated identification of elements for testing.

 

Element Type

Typical Naming

Custom Naming Convention

Purpose/Function

Button

class="btn btn-submit"

data-test="button-submit"

Button that submits a form

Input Field

id="email"

data-test="input-email"

Input field for email address

Navigation Link

class="nav-link"

data-test="link-home"

Link to the home page

Search Box

class="search"

data-test="input-search"

Input field for searching content

Expand/Collapse Icon

class="toggle-icon"

data-test="icon-expand"

Icon to expand a section of the UI

   

data-test="icon-collapse"

Icon to collapse a section of the UI

Product Card

class="product"

data-test="card-product-shoes"

Card representing a product (shoes) in a list

User Profile

class="user-profile"

data-test="card-profile-johndoe"

Profile card in a dashboard

Success Message

class="alert alert-success"

data-test="alert-success"

Message confirming successful action

Error Alert

class="alert alert-danger"

data-test="alert-error-login"

Alert message for a login failure

Loading Spinner

class="loading-spinner"

data-test="spinner-loading"

Spinner indicating content is loading

Modal Window

id="myModal"

data-test="modal-feedback"

Modal window for feedback

   

data-test="modal-confirmation"

Modal window for confirmations

 

This table adopts a data-test attribute for simplicity, but the exact attribute name (data-test, data-testid, data-pw, etc.) can be tailored to match your team's conventions or the specific requirements of the test automation framework you're using. The key is consistency and clarity in naming, ensuring that each attribute value provides immediate insight into the element's role and function, thereby facilitating more efficient and effective automated testing.

 

Conclusion

Custom test attributes are a powerful feature for enhancing test automation strategies. By configuring your test framework to recognize and utilize these attributes, teams can achieve more reliable, maintainable, and efficient automated testing. Remember, the key to successful test automation lies not only in the tools you use but also in the practices and conventions you establish within your team.

 

Afsal Backer

Afsal Backer is a test automation engineer with experience in building UI and API test automation frameworks, implementing CI pipelines for QA, and test execution in AWS. He has certifications from Test Automation University. Afsal often shares on his LinkedIn and blog.