To select an element by class you need to use . prefix and to select an element by its it, you should prefix id with # . The most common attribute you might find on your page would be a placeholder for an input or even a test-id where your selector starts and ends with square brackets.
The code below should do what you're trying to achieve. There is also an entire recipe with suggestions on how to test links that open in new tabs.
it('Advertise link should refer to Contact page', () => {
cy.get('div.footer-nav > ul > li:nth-child(2) > a')
.should('have.attr', 'href').and('include', 'contact')
.then((href) => {
cy.visit(href)
})
})
I would also suggest reading through the Cypress document on the best ways to assign and work with variables: https://on.cypress.io/variables-and-aliases
invoke("attr", "href")
Navigate to the URL specified in the element's href attribute:
cy.get(selector)
.invoke('attr', 'href')
.then(href => {
cy.visit(href);
});
Reference: https://docs.cypress.io/api/commands/invoke.html#Function-with-Arguments
Remove the target attribute from the anchor element, then click on it to navigate to its URL within the same tab:
cy.get(selector).invoke('removeAttr', 'target').click()
Reference: https://docs.cypress.io/examples/examples/recipes.html#Tab-Handling-and-Links
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With