Cypress get href attribute

JavascriptAutomated TestsCypress

Javascript Problem Overview


I have a test case in which I have a link which opens in a new tab. Since Cypress doesn't support multiple tabs, I want to get the href attribute of that link and then open it in the same tab. I'm trying to do it this way, but for some reason it doesn't work.

it('Advertise link should refer to Contact page', () => {
	var link = document.querySelector("div.footer-nav > ul > li:nth-child(2) > a").href;
	cy.visit(link);
	cy.title().should('include', 'Text');
});

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Solution 1: 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


Solution 2: Prevent content from opening in a new tab.

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

Solution 3 - Javascript

I resolved this issue:

First - check if href have right value

Second - create another test in which visit that href

Value for href was hard coded in my case.

Solution 4 - Javascript

I used something similar in a test:

cy.get('a').each(($el) => {
    const herf = $el.attr('href');
    cy.log(herf);

    // then I will do your test:
    cy.visit(link);
    cy.title().should('include', 'Text');

});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaxView Question on Stackoverflow
Solution 1 - JavascriptJennifer ShehaneView Answer on Stackoverflow
Solution 2 - JavascriptMobiletainmentView Answer on Stackoverflow
Solution 3 - JavascriptsrgjView Answer on Stackoverflow
Solution 4 - JavascriptMarco AmatoView Answer on Stackoverflow