Cypress - How to assert value of attribute?

Viewed 799

In a Cypress test, I'd like to assert that a given attribute exists on the page with a given value. The following works, but I'm wondering if there is a better way.

    cy.get('[data-page-id]').invoke('attr', 'data-page-id').should('eq', 'signupPage')
3 Answers

You can directly assert the attribute and value in one go like this example

cy.get('[data-page-id]').should('have.attr', 'data-page-id', 'signupPage')

This is equivalent

cy.get('[data-page-id="signupPage"]')

since .get() has a built-in assertion for all parts of the selector.

Although it is a bit verbose, what you have done is the recommended way to perform an assertion on an attribute.

Related