How to Check if Element has a Property in Cypress

How to Check if Element has a Property in Cypress

Ferenc Almasi β€’ 2021 October 14 β€’ Read time 1 min read
  • twitter
  • facebook

To check if an element has a specific property in Cypress, we can use the should('have.attr') assertion:

Copied to clipboard! Playground
// Check if anchor has href, rel, and download
cy.get('a').should('have.attr', 'href');
cy.get('a').should('have.attr', 'rel');
cy.get('a').should('have.attr', 'download');

// Combining it into one call
cy.get('a')
  .should('have.attr', 'href')
  .should('have.attr', 'rel')
  .should('have.attr', 'download');

Pass the property you would like to test as a second parameter. We can also use invoke in a similar way:

Copied to clipboard!
cy.get('div').invoke('attr', 'aria-label');
cy.get('div').invoke('attr', 'tabindex');
cy.get('div').invoke('attr', 'contenteditable');

The end result is the same. If you also need to check the value, we can do that too, by either using a third parameter for the should('have.attr') assertion or chaining a should after the invoke function:

Copied to clipboard! Playground
// Checking the value of a property using should('have.attr'):
cy.get('a').should('have.attr', 'href', '#value');
cy.get('a').should('have.attr', 'rel', 'noopener');

// Checking the value of a property using the invoke function:
cy.get('input').invoke('attr', 'name').should('eq', 'username'); // Should be equal
cy.get('input').invoke('attr', 'value').should('contain', 'username'); // Should contain

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to Check if Element has a property in Cypress
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.