In Cypress, retrieving attribute values of DOM elements is a common task that enables us to validate the state of various elements on the page. Cypress offers multiple approaches to retrieve attribute values, with the use of .invoke() and .should() methods being the most common practice. Below, I will detail the usage and examples of these two methods.
Using the .invoke() Method to Retrieve Attribute Values
The .invoke() method is used to call functions on an object. When applied to jQuery objects, we can retrieve the value of a specified attribute using .invoke('attr', 'attributeName').
Example Code:
javascript// Assume we want to retrieve the disabled attribute of a button cy.get('button#submit').invoke('attr', 'disabled').then(attr => { console.log(attr); // Output the attribute value });
In this example, cy.get('button#submit') first retrieves the button with ID submit, then uses .invoke('attr', 'disabled') to get the value of its disabled attribute, and processes it in the subsequent .then() block.
Using the .should() Method to Assert Attribute Values
Beyond retrieving attribute values for operations, we often need to verify that attribute values meet expected conditions, which can be achieved using the .should() method.
Example Code:
javascript// Verify if the button is disabled cy.get('button#submit').should('have.attr', 'disabled', 'disabled'); // Verify the alt attribute of an image cy.get('img#logo').should('have.attr', 'alt', 'Company Logo');
Here, should('have.attr', 'attributeName', 'expectedValue') is used to assert the attribute value of a DOM element. In the first example, we confirm that the button's disabled attribute is set to 'disabled'. In the second example, we verify that the image's alt attribute matches 'Company Logo'.
Both methods are highly effective and commonly used approaches for handling DOM element attributes in Cypress. By employing these techniques, we can ensure that the application's UI elements align with business requirements and user interaction expectations.