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:
// 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:
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:
// 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:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: