How to Assert Element Has Attribute in Cypress: Simple Guide
In Cypress, use
cy.get(selector).should('have.attr', attributeName) to assert that an element has a specific attribute. You can also check the attribute's value by adding a third argument with the expected value.Syntax
The basic syntax to assert an element has an attribute in Cypress is:
cy.get(selector): Selects the element(s) using a CSS selector..should('have.attr', attributeName): Asserts the element has the specified attribute..should('have.attr', attributeName, value): Optionally asserts the attribute has a specific value.
javascript
cy.get('selector').should('have.attr', 'attributeName') cy.get('selector').should('have.attr', 'attributeName', 'expectedValue')
Example
This example shows how to check if a button has the disabled attribute and if a link has the correct href value.
javascript
describe('Attribute Assertion Example', () => { it('checks element has attribute and value', () => { cy.visit('https://example.cypress.io') // Assert button has disabled attribute cy.get('button').should('have.attr', 'disabled') // Assert link has href attribute with specific value cy.get('a') .first() .should('have.attr', 'href', 'https://docs.cypress.io') }) })
Output
Test passes if the button has 'disabled' attribute and the first link's href equals 'https://docs.cypress.io'.
Common Pitfalls
Common mistakes when asserting attributes in Cypress include:
- Using incorrect selectors that do not match any element, causing the test to fail.
- Forgetting that
have.attrchecks for the attribute's presence; to check value, you must provide the expected value. - Trying to assert attributes on elements that are not yet rendered or visible.
javascript
/* Wrong: Missing attribute value check when needed */ cy.get('input').should('have.attr', 'type') // only checks presence /* Right: Check attribute and value */ cy.get('input').should('have.attr', 'type', 'text')
Quick Reference
| Command | Description |
|---|---|
| cy.get('selector').should('have.attr', 'attr') | Assert element has the attribute 'attr' |
| cy.get('selector').should('have.attr', 'attr', 'value') | Assert element's attribute 'attr' equals 'value' |
| cy.get('selector').should('not.have.attr', 'attr') | Assert element does NOT have the attribute 'attr' |
Key Takeaways
Use cy.get(selector).should('have.attr', attributeName) to check attribute presence.
Add the expected value as a third argument to assert attribute value.
Ensure your selector matches the element before asserting attributes.
Remember attribute assertions wait for the element to appear by default.
Use 'not.have.attr' to assert an attribute is missing.