Cypress get href attribute

I have a test case in which i have a link which opens in a new tab, and since cypress doesn't support multi tab, i wanna get 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.title().should('include', 'Text');



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) => {

I would also suggest reading through the Cypress document on the best ways to assign and work with variables:


Solution 1: invoke("attr", "href")

Navigate to the URL specified in the element's href attribute:

      .invoke('attr', 'href')
      .then(href => {


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()



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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.