'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:
Solution 1:[1]
cy
commands are asynchronous so for logging you need to use .then
:
cy.get('input').then(($input) => {
cy.log($input.attr('class'));
});
or
// with assertion
cy.get('input').should('have.attr', 'class').then(cy.log);
Solution 2:[2]
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])
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sree.Bh |
Solution 2 | themetzmeier |