Boris Frenkel
Boris Frenkel

Reputation: 353

How to get HTML attribute value in Cypress

I am starting to learn Cypress after few years working with Selenium. In Selenium i'm regularly using GetAttribute() method. As an exercise i'm trying to do the same with Cypress, to print class attribute value from the following HTML element:

<input class="form-control ng-touched ng-pristine ng-valid" max="21" min="1" type="number">

This is my code:

cy.log(cy.get('input').invoke('attr', 'class'));

Output:

log Object{5}

I tried to use Lakitna cypress-commands (https://github.com/Lakitna/cypress-commands) with the code:

cy.log(cy.get('input').attribute('class'));

Output:

enter image description here

Upvotes: 6

Views: 7820

Answers (2)

themetzmeier
themetzmeier

Reputation: 93

If you are looking for the value of the html tag and you end up here, this is the simplest way to do that:

            cy.get(`[data-testid="${key}"]`).then(($input) => {
            if($input.prop('nodeName') === "SELECT") {
                //Select corresponding input to value provided in dropdown lists

            } else {
                //Input each value provided into each field
                cy.get(`[data-testid="${key}"]`).clear().should('have.value', '').type(testMachine[key]).should('have.value', testMachine[key])
            }

Upvotes: 0

Sree.Bh
Sree.Bh

Reputation: 1789

cy commands are asynchronous so for logging you need to use .then:

cy.get('input').then(($input) => {
    cy.log($input.attr('class'));
});

screenshot1

or

// with assertion
cy.get('input').should('have.attr', 'class').then(cy.log);

screenshot2

Upvotes: 10

Related Questions