How to check for Attribute Values in Cypress?

July 2024 · 8 minute read

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. 

Table of Contents

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,…)

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. 

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.

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. 

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.

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.

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. 

Try Cypress Testing on Cloud

ncG1vNJzZmivp6x7o77OsKqeqqOprqS3jZympmeXqralsY6csKmqlajAbrPErWSarKSntqPB055kr5mcqrI%3D