Understanding the CM in Protractor
In the realm of software testing, Protractor is a powerful end-to-end test framework for Angular and AngularJS applications. It uses WebDriver to interact with the browser, and one of the key concepts you'll encounter is the use of CSS selectors to locate elements on the page. Among these, the 'cm' selector might pique your interest. Let's delve into where and how you can use the 'cm' in Protractor.
What is the 'cm' in Protractor?
The 'cm' in Protractor stands for 'custom attribute'. It allows you to select elements based on custom attributes you've defined in your application's HTML. This can be incredibly useful when you need to target elements that might otherwise be difficult to distinguish using standard CSS selectors.
Syntax of 'cm' in Protractor
The syntax for using 'cm' in Protractor is straightforward. It follows this pattern:

by.css('attribute^=value')
Here, 'attribute' is the name of the custom attribute, and 'value' is the value you're looking for. The '^=' operator means 'starts with'.
Where to Use 'cm' in Protractor
You can use 'cm' in Protractor wherever you need to locate elements based on custom attributes. Here are a few scenarios where it comes in handy:

- Unique Identifiers: If you need to target an element that has a unique custom attribute, 'cm' can help you locate it precisely.
- Dynamic Content: When dealing with dynamic content, standard CSS selectors might not work reliably. Using 'cm' can help you target elements even when their other attributes change.
- AngularJS Directives: In AngularJS applications, you might use custom attributes like 'ng-click', 'ng-model', etc. Protractor's 'cm' can help you interact with these elements.
Example: Using 'cm' to Locate an Element
Let's say you have the following HTML:
<div data-custom-attr="uniqueValue">...</div>
You can locate this element in Protractor using 'cm' like this:
var element = element(by.css('[data-custom-attr^="uniqueValue"]'));
Best Practices with 'cm' in Protractor
While 'cm' is a powerful tool, it's essential to use it judiciously. Here are some best practices:
- Use 'cm' sparingly. Over-reliance on custom attributes can make your tests brittle and difficult to maintain.
- Consider using data attributes (like 'data-custom-attr') for custom attributes. This keeps your HTML clean and makes it clear that these attributes are intended for automated testing.
- Ensure that the custom attributes you rely on are not changed or removed in future updates to your application.
Conclusion
The 'cm' in Protractor is a versatile tool that can help you locate elements based on custom attributes. Whether you're dealing with unique identifiers, dynamic content, or AngularJS directives, 'cm' can help you write more robust and reliable end-to-end tests. However, like any powerful tool, it's essential to use 'cm' judiciously and follow best practices to ensure the longevity and maintainability of your tests.