How to Check if Element has a Property in Cypress
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:
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews