How to check for Attribute Values in Cypress?

On This Page How to check for Attribute Values in Cypress?

June 16, 2026 · 9 min read · Tool Comparison

How to assure for Attribute Values in Cypress?

In, checking attribute values is essential for verify element behavior in your tests. Whether you need to corroborate a button is disabled, a link has the correcthref,or an image oodles from the right src, Cypress furnish powerful methods like.should() and .invoke()to get assertions easy.

Overview

Ways to ascertain for Attribute Values in Cypress

  • Use data-cy attributes
  • Use id picker
  • To assert your element is visible, use the .should () bid
  • Use the.within () command
  • To reuse selector, use the .as () command
  • To link several operations together, use the .and () and .invoke () commands
  • Reduce elements in a solicitation by apply the .filter () command
  • Access an particular from a collection using the .eq () dictation

This guide explore different agency to assure and assert attributes with virtual code examples.

How to check for Attribute Values in Cypress?

When try web applications with Cypress, verifying HTML attribute values is essential to ensure component behave and render correctly.

The HTML Element can have its Properties set via Attributes. They also help in defining how the elements act when a special stipulation is met and triggered. Almost all HTML tags have attributes, which function similarly to Cypress & # 8217; s NAME locater. Therefore, you can use the same approach to site elements using other characteristics as well.

The syntax for using attributes in Cypress is displayed below:

cy.get (& lt; tag & gt; [attribute_name=attribute_value])

Look at another scenario in which you want to use to locate all or a subset of the elements with attribute rubric that check the term & # 8220; trash & # 8221; (for example, trash-1, trash-2, & # 8230;)

  • Using the aforementioned syntax, one brute strength method is to happen each element separately along with its precise attribute value
  • But when you necessitate to search for multiple elements in Cypress and modify them with alike functional logic, this approach becomes time-consuming and ineffective.
  • Also, some web elements are give dynamically. For instance, checking a box on a web form might add another panel or battlefield to the user interface.
  • Alike to other elements, these frequently have dynamically created Class or Attribute names and lack a static ID or Class that you may reference withcy.get().

Read More:

Amazon provides an excellent manifestation of this; looking at the DOM there should yield you an idea of just how dynamic everything is. In the end, this is frequently the case with and other frontend library, which make choosing these pieces for an automated test challenging.

Using the regex-supported syntax in theCSS selectorto receive the list of target all at formerly would be a preferred scheme.

Read More:

Fortunately, Cypress offers a simpler solution, where you can utilize shape like starts-with and ends- with specific substring to match all of the DOM elements.

To identify all the element with values:

* =, cy.get (& lt; tags & gt; [attr_name * = attr_value])

Using attr_value as the start point, you may use:

^=, cy.get (& lt; tags & gt; [attr_name ^= attr_value])

To locate all the elements whose names finish in attr_value:

$ =, cy.get (& lt; tags & gt; [attr_name $ = attr_value])

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

Everything is asynchronous in Cypress. For representative, when you get an component withcy.get (& # 8216; yourcoolselector & # 8217;)you ’ re intellection of it as$ (& # 8216; yourcoolselector & # 8217;), but in fact, it ’ s an iterative process when trying to find this element from DOM. In other words, Cypress waits for a chooser within a certain timeout.

You will near surely interface with DOM, thereforecy.get is your best friend (). It guarantees that such an element is present on the page and permit entree to it and its children.

Read More:

1. data-cy attribute

You can afford your elements data-cy property, which are custom HTML attributes.

  • They permit Cypress to rapidly discover and choose specific page element without get to bank on complex XPath queries or.
  • Developers will find it unproblematic to establish tests quickly and accurately as a answer.
  • Making use ofdata-cyproperty can also create your codebase well-structured and manageable.
  • When making modifications or trouble-shoot problems in the futurity, you can quickly locate each part by giving it a descriptive name.

2. id selectors

id selectors are undependable since they are subject to change over time. Your exam will betray if you use an id selector to find an factor, and so that component & # 8217; s id changes afterwards. For this reason, it & # 8217; s best practice to stay away from id selectors when composing.

  • Try your better to use class or data-test property as selectors instead. Since they are less potential to change than ids, these picker are more dependable.
  • Additionally, if you & # 8217; re using a fabric like React, you can use its built-in testing usefulness to construct unique data-test dimension for each component.

On the same billet, selectors for XPath are sluggish and unstable. They might be challenging to read, troubleshoot, and maintain. Additionally, not all browsers support XPath selectors, thence they might not officiate as wait across different environments.

  • Use the built-in selector methods provided by Cypress kinda than XPath, such as .get () and .find ().
  • Compared to XPath chooser, these proficiency are faster and more reliable. They are also simpler to read and keep up with.

Learn More:

3. To assert your element is visible, use the .should () command

Using the .should()command, you may confirm that the element you are prefer is really present on the page. This do 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 & # 8217; t invalidate your tests because the.should()command will fail if the element can & # 8217; t be locate or isn & # 8217; t visible. Immediately agnize any modification to the page, can help you pass 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 '

Talk to an Expert

4. .within () command

Using the .within() dictation, you can limit the scope of a picker so that it only searches for elements inside the designated component. It & # 8217; s crucial that you use this command; otherwise, Cypress will search through every element on the page and can produce inaccurate results.

Consider two push that share the same class name but have distinct text values. Cypress can select the incorrect button if you don & # 8217; t use the.within()command. The .within () bid enables you to guarantee that Cypress performs its hunting but within the chosen element and gives the right answer.

cy.get ('.list ') .first () .within (($ list) = & gt; {}) // Yield the first ` .list ` and scope all commands within it

Read More:

5. To reprocess selectors, use the .as () dictation

You can save a selector in a variable with the .as () command, and you may subsequently reuse that varying several times throughout your test. By doing this, it becomes simpler to maintain trial over time and less code needs to be return.

Moreover, it ensures that you solely need to update the chooser once if the underlying HTML is changed rather than feature to rerun all of your tests to confirm their continued validity.

Read More:

6. To link various 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 transport out various activeness on a individual element or group of elements, this is helpful. The .and () command can perform two tasks simultaneously, such as clicking an element and so typing text into it.

Similar to the.and()command, the.invoke()dictation lets you call a function with arguments preferably than chain several activeness together. When testing complicated interactions, this can be used to transmit data from your test codification into the page being tested.

Read More:

7. 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 legion elements have the same class or ID gens, 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 & # 8220; push, & # 8221; for representative.
  • You could usecy.get (& # 8216; .button & # 8217;)instead ofcy.get (‘ .button ’). filter (‘ [data-test= ” myButton ”] ’)to get sure you & # 8217; re cull the correct element.
  • One of the sterling practices when work with Cypress chooser is to utilize the.filter() command because it makes sure you always choose the correct ingredient.

Must- Read:

8. Access an item from a collection habituate the .eq () dictation

The .eq () dictation allows you to access a specific element from an regalia of elements. This is essential since it guarantees that your test are independent of the DOM constituent order. Your tests might not legislate if the elements & # 8217; order changes if you use early methods, like .first () or .last (). Your codification becomes more understandable and simple to hold when you use the .eq () command. In contrast to depending on an index number, it is lots more obvious when you can see only the element you are get for.

What & # 8217; s the difference between .then () and .should () /.and ()?

When you need to change some values or perform some action, you should use the.then()since it enables you to use the yielded subject in a callback function.

  • On the former side, there is unique logic to repeatedly run the callback function until no assertions throw within it when utilizing a recall mapping with .should () or .and ().
  • Any side effects in a .should () or .and () recall function that you wouldn & # 8217; t desire to be repeated should be avoided.

Conclusion

Validating dimension values in Cypress is a simple yet powerful way to ascertain your web factor conduct as expected. Whether you are ensure forhref, class, disable, or any custom attribute, Cypress furnish intuitive commands like.should () and .invoke ()to make these verifications seamless and reliable.

To scale your Cypress trial across multiple browsers and go systems, consider using. It enable you to run Cypress exam in analogue on real devices and browsers helping you get issues quicker, ensure, and quicken your release cycles.

Tags
88,000+ Views

# Ask-and-Contributeabout this subject with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free