Within Cypress, to retrieve the href attribute of an element, you can use the .invoke('attr', 'attributeName') method, where attributeName specifies the attribute you wish to obtain, such as href. Here's a simple example demonstrating how to retrieve the href attribute of a link (anchor tag <a>):
javascript// Assume there is a link <a id="my-link" href="/some-path">Click here</a> // Use Cypress to select this element and retrieve the href attribute cy.get('#my-link') // Select the element .invoke('attr', 'href') // Retrieve the href attribute .then(href => { // Now you can use the href variable, which contains the link's href attribute value console.log(href); // Output: /some-path // Perform other assertions or operations });
In this example, the .get('#my-link') command first selects the element with the ID my-link, followed by the .invoke('attr', 'href') command to retrieve the href attribute value. Finally, .then() is used to obtain this value, enabling further operations or assertions on href within the callback function.
If you need to assert whether the href attribute has a specific value, you can directly use Cypress's .should() assertion method, for example:
javascript// Assert that the element's href attribute equals a specific value cy.get('#my-link').should('have.attr', 'href', '/some-path');
In this assertion, should('have.attr', 'href', '/some-path') verifies that the selected element has an href attribute with the value /some-path. If it does not match, the test fails.