How to check for Attribute Values in Cypress?
By Hamid Akhtar, Community Contributor - February 10, 2023
Developers commonly bring up unit tests when discussing testing. There is a lot more to it than that, though, and even having unit tests that cover every line of your code won’t guarantee the accuracy of the output from your application. We won’t rehash Cypress’ excellent documentation, which is already available at, but we would like to offer some valuable tips.
We will go over some prerequisites (for example, Cypress get attribute value) here and touch on other important topics as well.
- How to check for Attribute Values in Cypress?
- The HTML Element can have its Properties set via Attributes
- data-cy attributes
- id selectors
- To assert your element is visible, use the .should() command
- .within() command
- To reuse selectors, use the .as() command
- To link several operations together, use the .and() and .invoke() commands
- Reduce elements in a collection by using the .filter() command
- Access an item from a collection using the .eq() command
How to check for Attribute Values in Cypress?
The HTML Element can have its Properties set via Attributes
They also assist in defining how the elements act when a particular condition is met and triggered. Almost all HTML tags have attributes, which function similarly to Cypress’s NAME locator. Therefore, we can use the same approach to locate elements using other characteristics as well.
The syntax for using attributes in Cypress is displayed below:
cy.get(<tag>[attribute_name=attribute_value])
Let’s look at another scenario in which you want to use Cypress to locate all or a subset of the elements with attribute titles that contain the term “trash” (for example, trash-1, trash-2,…)
- Using the aforementioned syntax, one brute force method is to find each element separately along with its precise attribute value
- But when we need to search for multiple elements in Cypress and change them with similar functional logic, this approach becomes time-consuming and ineffective.
- Also, some web elements are generated dynamically. For instance, checking a box on a web form might add another panel or field to the user interface.
- Similar to other elements, these frequently have dynamically created Class or Attribute names and lack a static ID or Class that we may reference with cy.get().
Amazon provides an excellent demonstration of this; looking at the DOM there should give you an idea of just how dynamic everything is. In the end, this is frequently the case with React and other frontend libraries, which makes choosing these pieces for an automated test challenging.
Using the regex-supported syntax in the CSS selector to obtain the list of objects all at once would be a preferable strategy.
Fortunately, Cypress offers a simpler solution, where you can utilize patterns like starts-with and ends- with specific substring to match all of the DOM elements.
To identify all the elements with values:
*=, cy.get(<tags>[attr_name *= attr_value])
Using attr_value as the starting point, we may use:
^=, cy.get(<tags>[attr_name ^= attr_value])
To locate all the elements whose names finish in attr_value:
$=, cy.get(<tags>[attr_name $= attr_value])
Everything is asynchronous in Cypress. For example, when you get an element with cy.get(‘yourcoolselector’) you’re thinking of it as $(‘yourcoolselector’), but in fact, it’s an iterative process when trying to find this element from DOM. In other words, Cypress waits for a selector within a certain timeout.
You will almost certainly interface with DOM, therefore cy.get is your best friend (). It guarantees that such an element is present on the page and allows access to it and its children.
data-cy attributes
You can give your elements data-cy attributes, which are custom HTML attributes.
- They allow Cypress to rapidly discover and choose specific page elements without having to rely on complex XPath queries or CSS selectors.
- Developers will find it simpler to build tests quickly and accurately as a result.
- Making use of data-cy attributes can also make your codebase well-structured and manageable.
- When making modifications or troubleshooting problems in the future, you can quickly locate each part by giving it a descriptive name.
id selectors
id selectors are unreliable since they are subject to change over time. Your test will fail if you use an id selector to find an element, and then that element’s id changes afterwards. For this reason, it’s best practice to stay away from id selectors when composing Cypress tests.
- Try your best to use class or data-test attributes as selectors instead. Since they are less likely to change than ids, these selectors are more dependable.
- Additionally, if you’re using a framework like React, you can use its built-in testing utilities to construct unique data-test attributes for each component.
On the same note, selectors for XPath are sluggish and unstable. They might be challenging to read, troubleshoot, and maintain. Additionally, not all browsers support XPath selectors, thus they might not function as expected across different environments.
- Use the built-in selector methods provided by Cypress rather than XPath, such as .get() and .find().
- Compared to XPath selectors, these techniques are faster and more reliable. They are also simpler to read and keep up with.
Learn More: Quick XPath Locators Cheat Sheet
To assert your element is visible, use the .should() command
Using the .should() command, you may confirm that the element you are choosing is truly present on the page. This makes sure that the element you are trying to pick is indeed there and visible in the DOM, preventing false positives from occurring when your tests are run.
Additionally, it ensures that any page changes don’t invalidate your tests because the .should() command will fail if the element can’t be located or isn’t visible. Immediately recognizing any changes to the page, can help you spend less time troubleshooting problems with your tests.
cy.get('.error').should('be.empty') // Assert that '.error' is empty cy.contains('Login').should('be.visible') // Assert that el is visible cy.wrap({ foo: 'bar' }).its('foo').should('eq', 'bar') // Assert the 'foo' property equals 'bar'
.within() command
Using the .within() command, you can limit the scope of a selector so that it only searches for elements inside the designated element. It’s crucial that you use this command; otherwise, Cypress will search through every element on the page and can produce inaccurate results.
Consider two buttons that share the same class name but have distinct text values. Cypress can choose the incorrect button if you don’t use the .within() command. The .within() command enables you to guarantee that Cypress performs its search only within the chosen element and gives the right answer.
cy.get('.list') .first() .within(($list) => {}) // Yield the first `.list` and scope all commands within it
To reuse selectors, use the .as() command
You can save a selector in a variable with the .as() command, and you may subsequently reuse that variable several times throughout your test. By doing this, it becomes simpler to maintain tests over time and less code needs to be generated.
Moreover, it ensures that you only need to update the selector once if the underlying HTML is changed rather than having to rerun all of your tests to confirm their continued validity.
To link several operations together, use the .and() and .invoke() commands
By chaining several actions together, you can have them all run at once using the .and() command. When you have to carry out several actions on a single element or group of elements, this is helpful. The .and() command can perform two tasks simultaneously, such as clicking an element and then typing text into it.
Similar to the .and() command, the .invoke() command lets you call a function with arguments rather than chaining several actions together. When testing complicated interactions, this can be used to transmit data from your test code into the page being tested.
Reduce elements in a collection by using the .filter() command
Cypress will return all matched elements when you use a selector to locate elements on the page. If numerous elements have the same class or ID name, this could be a problem. To get over this problem, you should utilise the. filter() function to reduce your selection and pick just the right element.
- Take the case where you want to click on an element with the class “button,” for instance.
- You could use cy.get(‘.button’) instead of cy.get(‘.button’). filter(‘[data-test=”myButton”]’) to make sure you’re picking the right element.
- One of the greatest practices when working with Cypress selectors is to utilize the .filter() command because it makes sure you always choose the correct element.
Must- Read: Cypress Best Practices for Test Automation
Access an item from a collection using the .eq() command
The .eq() command allows you to access a specific element from an array of elements. This is essential since it guarantees that your tests are independent of the DOM element order. Your tests might not pass if the elements’ order changes if you use other methods, like .first() or .last(). Your code becomes more understandable and simple to maintain when you use the .eq() command. In contrast to depending on an index number, it is much more obvious when you can see just the element you are aiming for.
What’s the difference between .then() and .should()/.and()?
When you need to change some values or perform some actions, you should use the .then() since it enables you to use the yielded subject in a callback function.
- On the other side, there is unique logic to repeatedly run the callback function until no assertions throw within it when utilizing a callback function with .should() or .and().
- Any side effects in a .should() or .and() callback function that you wouldn’t want to be repeated should be avoided.
Closing Notes
With Cypress Get Attribute values clear, it is time to integrate Cypress tests with BrowserStack Automate. Apart from that, we’ll assume you’re merging an existing Cypress project. If you don’t have access to an active Cypress project, try performing your initial test using the Cypress Kitchen Sink web application.
By accessing BrowserStack cloud infrastructure, QA teams can opt for hassle-free Cypress parallelization as well.